/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Album.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */

define(
    '../entrance_record/Ancestor',['require','exports','module'],function(require, exports, module) {
        window.Ancestor = window.Ancestor || {
            version: '1.0'
        };
        window.SystemDialog = (function () {
            var doHandler = null;
            var _initAlert = false;
            var _initConfirm = false;

            function initAlertDlg() {
                if (!_initAlert) {
                    if ($("#epg_alert_dlg").length == 0) {
                        $('body').append('<div id="epg_alert_dlg"><div sign="detail"></div></div>');
                    }
                    $("#epg_alert_dlg").dialog({
                        title: "epg系统提醒",
                        autoOpen: false,
                        width: 400,
                        modal: true,
                        dialogClass: 'alert',
                        resizable: false,
                        closeOnEscape:false,
                        buttons: [
                            {
                                text: "确认",
                                click: function () {
                                    $(this).dialog("close");
                                }
                            }
                        ]
                    })
                    _initAlert = true;
                }
                console.log("_initAlert:" + _initAlert);
            }

            function initConfirmDlg() {
                if (!_initConfirm) {
                    if ($("#epg_confirm_dlg").length == 0) {
                        $('body').append('<div id="epg_confirm_dlg"><div sign="detail"></div></div>');
                    }
                    $("#epg_confirm_dlg").dialog({
                        title: "epg系统确认",
                        autoOpen: false,
                        width: 400,
                        modal: true,
                        dialogClass: 'alert',
                        resizable: false,
                        closeOnEscape:false,
                        buttons: [
                            {
                                text: "确认",
                                click: function () {
                                    $(this).dialog("close");
                                    doHandler(true);
                                }
                            },
                            {
                                text: "取消",
                                click: function () {
                                    $(this).dialog("close");
                                    doHandler(false);
                                }
                            }
                        ]
                    });
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(1)").addClass("btn btn-primary");
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(2)").addClass("btn");
                    _initConfirm = true;
                }
                console.log("_initConfirm:" + _initConfirm);
            }

            function queryAlert(msg) {
                initAlertDlg()
                $("#epg_alert_dlg").find("div[sign=detail]").html(msg);
                $("#epg_alert_dlg").dialog("open");
            }

            function queryConfirm(msg, callback,btnNameObj) {
                initConfirmDlg();
                $("#epg_confirm_dlg").find("div[sign=detail]").html(msg);
                var btnExtend = $.extend(true,{"btn_ok":"确认","btn_cancel":"取消"},btnNameObj);
                if( "btn_ok" in btnExtend){
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(1)").html(btnExtend["btn_ok"])
                }
                if( "btn_cancel" in btnExtend){
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(2)").html(btnExtend["btn_cancel"])
                }
                $("#epg_confirm_dlg").dialog("open");
                doHandler = function (flag) {
                    if (typeof(callback) == "function") {
                        callback(flag);
                    }
                }
            }

            return {
                queryAlert: queryAlert,
                queryConfirm: queryConfirm
            }
        })();

    }
);
define(
    '../entrance_record/Ancestor.Auth',['require','exports','module'],function (require, exports, module) {
        Ancestor.Auth = (function () {
            var baseInfo = {
                authUrl: '/api/permission',
                loginUrl: 'http://lego.iqiyi.com/login?url=http://lego.iqiyi.com%2F',
                url403: 'http://lego.iqiyi.com/common/403.jsp',
                loginOut: 'http://lego.iqiyi.com/logout',
                navListUrl: 'http://ulive.lego.iqiyi.com/live-web/services/liveNav.do',
                authInfo: null,
                tips: 0 //0 304页面提示 1头部标签提示
            }
            var jump2TargetPage = function (url) {
                window.location.href = url;
            }
            var getDev = function () {
                return parseInt(Com.cookie.get('dev'));
            };

            function getVersion(){
                return "4.3.180";
            }

            function setWaring(tips) {
                var warning = '<div  style="display:block;position: fixed;top: 5px;left: 10%;width: 80%;z-index: 100000;text-align: center;height: 26px;line-height: 26px;color: red;background: #fff1d3;margin-bottom: 16px;text-shadow: 0 1px 0 rgba(255,255,255,0.5);"><strong>提示!</strong> ' + tips + '</div>';
                return warning;
            }

            // ajax 请求
            var getAuthData = function (options, callback) {
                options = options || {};
                var url = url || Com.url.parse(window.location.href)['path'];
                var tempBaseInfo = $.extend(true,{url:url} , baseInfo, options);
                Ancestor.Dao.ajax({
                    url: tempBaseInfo.authUrl,
                    dataType: 'json',
                    method: 'get',
                    cache: false,
                    //async: false,
                    data: {'uri': tempBaseInfo.url.split('?')[0]},
                    success: function (data) {
                        //console.log(data);
                        if (options.tips) {
                            //   if (baseInfo.tips) {
                            if (data.code == 'A00304')
                                callback.call(this, 1);   // 无权限
                            else
                                callback.call(this, null); // 有权限
                            return;
                        }
                        switch (data.code) {
                            case 'A00000': // 已登陆
                                tempBaseInfo.authInfo = data.data;
                                var newDev = 0;
                                if (tempBaseInfo.authInfo.devMode) {
                                    newDev = 1
                                }
                                var dev = getDev();
                                showLogInfo( tempBaseInfo );
                                callback.call(this, "suc")
                                if (dev == NaN || dev != newDev) {
                                    Com.cookie.set('dev', newDev);
                                    window.location.reload();
                                }
                                break;
                            case 'A00303': // 未登陆
                            case 'A00401':
                                jump2TargetPage(tempBaseInfo.loginUrl);
                                break;

                            case 'A00304': // 无权限
                                //jump2TargetPage(baseInfo.url403);
                                var warning = setWaring('sorry,您没有操作本页面的权限！');
                                $('body').html('');
                                $('body').html(warning);
                                break;
                        }
                    },
                    error: function (data) {
                        var warning = setWaring('网络故障,<a href="javascript:void(0);" onclick = "window.location.reload();">请重刷！</a>');
                        $('body').html(warning);
                    }
                }, "/permission")

            }

            function queryNavList(baseInfo){
                var request = {};
                request.url = baseInfo.navListUrl;
                request.type = 'get';
                request.params = {};
                request.needCookie = true;
                request = JSON.stringify(request);
                Ancestor.Dao.redirectRequest({request: request} , function(data){
                    if(!data) {
                        console.warn(" 获取导航条失败!")
                        return;
                    }
                    Ancestor.Util.buildMenu(  data )
                } )
            }

            function showLogInfo(baseInfo) {
                var epg_version = auth.version() + (auth.dev() ? "_test" : "_production");
                Ancestor.Util.buildHeader();
                Ancestor.Util.buildUserInfo(baseInfo);
                Ancestor.Util.buildFooter(epg_version);
                $("#BackToTopButton").bind("click",function(){
                    $("html,body").animate({"scrollTop":0})
                })
                $(window).bind('scroll', function () {
                    Com.page.scrollToTop($("#BackToTopButton"));
                });
                queryNavList(baseInfo)
            }

            return{
                getAuthData: getAuthData,
                baseInfo: baseInfo,
                jump2TargetPage: jump2TargetPage,
                dev: getDev, //开发环境
                version:getVersion
            };
        })();
        var auth = Ancestor.Auth;
        var dev = auth.dev();
        window.auth = auth;
        window.dev = dev;
        console.log(" window.auth done");
    }
);
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file: Ancestor.Base.js
 * @path: js-src/Ancestor/
 * @desc: Ancestor模块下基础业对象类
 * @author: lichuning@qiyi.com
 * @date: 2013-04-10
 */
///import js-src/lib/
///import js-src/com/

define('../entrance_record/Ancestor.Grid',['require','exports','module'],function (require, exports, module) {

    Ancestor.Grid = function (options) {
    };
    /**
     * 每个Action都设置一个初始化方法 用于初始化Ancestor 原型对象，默认不重复初始化
     *
     * @param {Boolean}
     *            force 是否强制初始化
     *
     */
    Ancestor.Grid.prototype = $.extend(true, {}, Com.Grid, {
        /**
         * 素材库查询方法
         * @param params 查询参数，采用jquery formSerialize
         * @param callback
         */
        query: function (callback) {

            var self = this;
            var $grid = self.$grid;

            var params = this.getParam();

            $grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid', [
                {
                    page: 1
                }
            ]);

        },
        getParam: function () {

            var self = this;
            var $container = self.options.$container;
            var $grid = self.$grid;
            Com.Grid.overridePostData($grid);
            var params = {};
            var $elements = $.makeArray($container.find('form.query').prop('elements'));

            $.each($elements, function () {
                if (this.name) {
                    var key = $(this).attr('data-key');
                    if (key) {
                        params[this.name] = $(this).attr(key) || '';
                    } else {
                        params[this.name] = $(this).val();
                    }
                }
            });

            return params;
        },

        echoQuery: function () {
            var self = this;
            var $container = self.options.$container;

            this.query();

        },

        getGridConfig: function (table, tableColModel) {
            var self = this;
            var tableConfig = $.extend(true, {}, table || self.config.TABLE);
            var colModel = tableConfig.colModel;
            var newColModel = [];
            var colModelConfig = tableColModel || self.config.TABLE_COLMODEL_CONFIG;

            $.each(colModel, function (i, model) {
                newColModel.push(colModelConfig[model]);
            });
            tableConfig.colModel = newColModel;
            return tableConfig;
        },

        initGrid: function (options, callback) {
            var self = this;

            var gridConfig = self.getGridConfig();

            var $gridContainer = self.options.$container;

            var type = self.getType();
            var $pager = $gridContainer.find('div.pager');
            var $grid = $gridContainer.find('table.grid');
            var params = self.getParam();
            options = $.extend(true, {
                pager: $pager,
                mtype: 'post',

                postData: $.extend(true, {
                    type: type

                }, params),

                sortname: 'createTime',
                sortorder: 'desc',


                multiselect: true,

                multiselectWidth: 30

            }, gridConfig, options);

            $grid.jqGrid('scroll', {});
            $grid.jqGrid(options);

        },

        reload: function (params) {
            var type = this.getType();
            params = $.extend(true, {
                type: type
            }, params);
            this.$grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid');
        }


    })
});


/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../entrance_record/Ancestor.Config',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    window.GLOBAL =   window.GLOBAL || {};
    GLOBAL.user = {
        area: "sh"
    };
    GLOBAL.currentDate = Com.date.getCurrentDate();

    Ancestor.Config = (function() {
        var EPG_AUTH = {
            From: 'frontend', // 来源
            key: '7dpHGKMy4hAh3DmC' // 密钥
        };
        return {
            EPG_AUTH: EPG_AUTH
        };
    })();

});
/**
 * @file:   Ancestor.Util.js
 * @path:   js/Ancestor/
 * @desc:
 * @author: karkarrotxu@qiyi.com
 * @date:   2017-08-15
 */
define('../entrance_record/Ancestor.Util',['require','exports','module'],function (require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    window.Ancestor = window.Ancestor || {
        version: '1.0'
    };
    Ancestor.Util = (function () {
        // 组装 sign
        var authorization = function (options) {
            var rawSign = options.url + options.clientTime + Ancestor.Config.EPG_AUTH.key;
            return qui.md5("hashString", rawSign);
        };

        var getUrlId = function (name) {

            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return r[2];
            return null;
        };

        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function ($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function (textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function () {
                    t(this);
                },
                propertychange: function () {
                    t(this);
                },
                keyup: function () {
                    t(this);
                }
            });
            $des.keyup();
        };
        var getAuth = function (str) {
            var auth = {
                    'sign': '',
                    'clientTime': '',
                    'from': ''
                },
                time = parseInt(new Date().getTime() / 1000);
            auth.from = Ancestor.Config.EPG_AUTH.From;
            auth.clientTime = time;
            auth.sign = qui.md5("hashString", str + time + Ancestor.Config.EPG_AUTH.key);
            return auth;

        };

        var buildHeader = function(){
            var node1 = $('<nav class="navbar navbar-default navbar-fixed-top" role="navigation"></nav>');
            var node2 = $('<div class="container-fluid"></div>')
            var node2_1 = $('<div class="navbar-header"></div>');
            var node2_1_1 = $('<a class="navbar-brand" href="http://lego.iqiyi.com">LEGO</a>');
            var node2_2 = $('<div class="collapse navbar-collapse"></div>');
            node2_1_1.appendTo(node2_1);
            node2_1.appendTo(node2);
            node2_2.appendTo(node2);
            node2.appendTo(node1);
            node1.appendTo($("header.main-header"));
        }


        var buildMenu = function (usrData) {
            var parent = $("header div.navbar-collapse")
            var node5 = $('<ul class="nav navbar-nav j-lego-nav"></ul>');
            var node6 = $('<li class="dropdown "></li>');
            var node6_1 = $('<a href="javascript:;" class="dropdown-toggle">直播中心 <span class="caret"></span></a>');
            var node6_2 = $('<ul class="dropdown-menu dropdown-sub-nav" role="menu" data-cid="live"></ul>');
            var navListData = [];
            $.each(usrData, function (i, element) {
                navListData.push('<li class="navbar-sub-nav">');
                navListData.push(' <div class="navbar-sub-title"><span class="glyphicon glyphicon-th-large"></span>' + element.name + '</div>');
                navListData.push('<ul class="navbar-sub-list list-inline">');
                $.each(element.items, function (j, child) {
                    navListData.push('<li><a href="' + child.url + '" target="_blank">' + child.name + '</a></li>');
                })
                navListData.push('</ul>');
                navListData.push('</li>');
            })
            $(navListData.join("")).appendTo(node6_2);
            node6_1.appendTo(node6);
            node6_2.appendTo(node6);
            node6.appendTo(node5);
            node5.appendTo(parent);
        }
        var buildUserInfo = function (usrData) {
            var parent = $("header div.navbar-collapse")
            var htmlArr = [];
            htmlArr.push('  <ul class="nav navbar-nav navbar-right">');
            htmlArr.push('    <li class="dropdown" style="right: 30px">');
            htmlArr.push('         <a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"><span class="glyphicon glyphicon-user"></span>' + usrData.authInfo.userName + '</a>');
            htmlArr.push('        <ul class="dropdown-menu dropdown-user-info" role="menu"> ');
            htmlArr.push('            <li class="user-header"> ');
            htmlArr.push('               <p>' + usrData.authInfo.userName + '</p> ');
            htmlArr.push('                 <p><small>UID: ' + usrData.authInfo.uid + '</small></p> ');
            htmlArr.push('          </li>');
            htmlArr.push('           <li class="user-footer clearfix">');
            htmlArr.push('              <div class="text-center">');
            htmlArr.push(' <a href="'+usrData.loginOut+'" class="btn btn-default btn-block" data-ripple-color="#444">退出</a>');
            htmlArr.push('  </div></li></ul></li></ul>');
            parent.append(htmlArr.join(""));
        }

        var buildFooter = function (epg_version) {
            var htmlArr = [];
            htmlArr.push(' <footer class="main-footer">')
            htmlArr.push('   <div class="scroll-to-top scroll-to-top-hide" id="BackToTopButton">')
            htmlArr.push('     <a class="btn" href="javascript:;"><i class="glyphicon glyphicon-circle-arrow-up"></i>返回顶部</a>')
            htmlArr.push('  </div>')
            htmlArr.push('    <div class="container">')
            htmlArr.push('        <div class="footer-content">')
            htmlArr.push('           <p class="text-center">' + epg_version + ' Copyright © 2018 <a href="//www.iqiyi.com">iQIYI.COM</a> All rights reserved.</p>')
            htmlArr.push('           <p class="text-center">请使用 Chrome，Firefox，IE10+ 等浏览器访问本站</p>')
            htmlArr.push('       </div>')
            htmlArr.push('    </div>')
            htmlArr.push('  </footer>');
            $("body").append(htmlArr.join(""));
        }

        return {
            authorization: authorization,
            getUrlId: getUrlId,
            limitWordCount: limitWordCount,
            getAuth: getAuth,
            buildMenu: buildMenu,
            buildUserInfo: buildUserInfo,
            buildFooter: buildFooter,
            buildHeader:buildHeader
        };
    })();

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-12
 */
define(
    '../entrance_record/Ancestor.Dao',['require','exports','module'],function(require, exports, module) {

        Ancestor.Dao = (function() {
            var ajax = function(options, authPath) {
                if (authPath)
                    $.ajax($.extend(options, {
                        beforeSend: function(request) {
                            var authBase = Ancestor.Util.getAuth(authPath);
                            request.setRequestHeader('Sign', authBase.sign);
                            request.setRequestHeader("Time", authBase.clientTime);
                            request.setRequestHeader("From", authBase.from);
                            request.setRequestHeader("UserName", (auth.baseInfo.authInfo==null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                        }
                    }));
                else
                    $.ajax(options);
            };

            // XMLHttp Request
            var _getXHR = function() {
                return new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHTTP') || new ActiveXObject('Microsoft.XMLHTTP');
            };

            var redirectRequest = function(options, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: options,
                    method: 'post',
                    beforeSend: function(request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/redirect");
            };

            return {
                redirectRequest: redirectRequest,
                ajax: ajax
            };
        })();
    }
);

define(
    '../epg2/EpgWeb',['require','exports','module'],function(require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };

        EpgWeb.Constant = {
            //baseApiUrl:"http://test.admin.epg.qiyi.domain/api/",
            baseApiUrl: "/api/",
            thirdUrl_audit_people: "http://lego.iqiyi.com/suggest/audit-people",
            originalUrl: "http://10.23.84.18:8500/",
            third_location_url:"http://lego.iqiyi.com/suggest/region",
            thirdUrl_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/get_id_by_name",
            thirdUrl_add_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/add_resource",
            thirdUrl_video_url: "http://lego.iqiyi.com/suggest/simple-video",
            thirdUrl_album_url: "http://lego.iqiyi.com/suggest/album",
            thirdUrl_playlist_url: "http://lego.iqiyi.com/suggest/playlist",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list",
            thirdUrl_video_area_url: "http://lego.iqiyi.com/suggest/simple-video-area",
            thirdUrl_album_area_url: "http://lego.iqiyi.com/suggest/album-area",
            thirdUrl_apis_search_area_url: "http://lego.iqiyi.com/apis/search/search-area",
            thirdUrl_category_first_list_url:"http://lego.iqiyi.com/apis/category/live-first-list",
            // use for child secLv thirdLv
            thirdUrl_category_child_list_url: "http://lego.iqiyi.com/category/list",
            thirdUrl_passport_url:"http://passport.qiyi.domain/apis/internal/user_info.action",
            devMode: auth.dev()
        }
        EpgWeb.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var programListUrl = useUrl + "program/list";
            var programListSortUrl = useUrl + "program/listSort";
            var programAddUrl = useUrl + "program/add";
            var programDelUrl = useUrl + "program/delete";
            var programEditUrl = useUrl + "program/edit";
            var programLogUrl = useUrl + "program/loglist";
            var configsUrl = useUrl + "configs";
            var channelListUrl = useUrl + "channel/list";
            var programSyncUrl = useUrl + "program/syncTVMao";
            var redirectUrl = useUrl + "redirect";
            var channelGetUrl = useUrl + "channel/get";
            var queryPuYuUrl = useUrl + "program/queryPuYu";
            var carouselRuleListUrl = useUrl + "carousel/get";
            var carouselRuleDelUrl = useUrl + "carousel/del";
            var carouselRuldAddUrl = useUrl + "carousel/create";
            var programLiveQueryUrl = useUrl + "program/liveQuery";
            var programMoveUrl = useUrl + "program/move";
            var programToggleLockUrl = useUrl + "program/toggleLock";
            var programBatchAddUrl = useUrl + "program/batchAdd";
            var carouselEpisodeBatchAddUrl = useUrl + "carousel/carouselEpisode/batchAdd";
            var carouselEpisodeBatchDelUrl= useUrl + "carousel/carouselEpisode/batchDel";
            var carouselEpisodeListUrl= useUrl + "carousel/carouselEpisode/list";
            var carouselEpisodeIndexMoveUrl= useUrl + "carousel/carouselEpisode/indexMove";
            var carouselEpisodeIndexMoveByIndexUrl= useUrl + "carousel/carouselEpisode/indexMove/byIndex";
            var programDaySortUrl = useUrl + "program/daySort";
            var programIndexMoveUrl = useUrl + "program/indexMove";
            var programBatchDelUrl = useUrl + "program/batchDel";
            var platSettingsGetUrl = useUrl + "channel/getPlatSettings";
            var yesterdayEndTimeUrl = useUrl + "program/yesterdayEndTime";
            var automationAddUrl = useUrl + "carousel/automation/add";
            var automationDelUrl = useUrl + "carousel/automation/del";
            var automationListUrl = useUrl + "carousel/automations";
            var automationMoveUrl = useUrl + "carousel/automation/indexMove";
            var automationMoveByIndexUrl = useUrl + "carousel/automation/indexMove/byIndex";
            var automationChangeStatusUrl = useUrl + "carousel/automation/changeStatus";
            var getBroadcastControlsUrl = useUrl+"broadcast/controls";
            var reservation_create_Url = useUrl+ "reservation";
            var reservation_del_Url = useUrl+ "reservation/del";
            var reservation_edit_Url = useUrl+"reservation/edit";
            var reservation_get_Url = useUrl+ "reservations";
            var setBroadcastControlAllUrl= useUrl+"broadcast/controlall";
            var setBroadcastControlUrl  = useUrl+"broadcast/control";
            var platSettingsSaveUrl =  useUrl+"channel/savePlatSettings";
            var programBroadcastControlUrl =  useUrl+"program/broadcast/control";
            var programForceCheckUrl = useUrl + "program/forceCheck";
            var advertModifyUrl  = useUrl + "advert/modify";
            var directorCreateUrl =  useUrl + "director/create";
            var notifyAlertUrl = useUrl + "notify/alertPlatform";
            function getQiPuBaseUrl(qipuId){
                var plusUrl = EpgWeb.Constant.devMode ? "http://qipu-test.qiyi.domain/int/entity/nocache/@.json" : "http://qipu.qiyi.domain/int/entity/nocache/@.json";
                return plusUrl.replace("@", "" + qipuId);
            }
            return {
                programList: programListUrl,
                programListSortUrl: programListSortUrl,
                programAdd: programAddUrl,
                programDel: programDelUrl,
                programEdit: programEditUrl,
                programLog:programLogUrl,
                programForceCheck:programForceCheckUrl,
                configs: configsUrl,
                channelList: channelListUrl,
                channelGet: channelGetUrl,
                programSyncUrl: programSyncUrl,
                queryPuYu: queryPuYuUrl,
                carouselRuleListUrl: carouselRuleListUrl,
                carouselRuleDelUrl: carouselRuleDelUrl,
                carouselRuldAddUrl: carouselRuldAddUrl,
                carouselEpisodeBatchAddUrl:carouselEpisodeBatchAddUrl,
                carouselEpisodeBatchDelUrl:carouselEpisodeBatchDelUrl,
                carouselEpisodeListUrl:carouselEpisodeListUrl,
                carouselEpisodeIndexMoveUrl:carouselEpisodeIndexMoveUrl,
                carouselEpisodeIndexMoveByIndexUrl:carouselEpisodeIndexMoveByIndexUrl,
                programLiveQueryUrl: programLiveQueryUrl,
                programMoveUrl: programMoveUrl,
                programToggleLockUrl: programToggleLockUrl,
                programDaySortUrl: programDaySortUrl,
                programBatchAddUrl: programBatchAddUrl,
                programIndexMoveUrl: programIndexMoveUrl,
                programBatchDelUrl: programBatchDelUrl,
                platSettingsGetUrl: platSettingsGetUrl,
                yesterdayEndTimeUrl: yesterdayEndTimeUrl,
                automationAddUrl: automationAddUrl,
                automationDelUrl: automationDelUrl,
                automationListUrl: automationListUrl,
                automationMoveUrl: automationMoveUrl,
                automationChangeStatusUrl: automationChangeStatusUrl,
                reservationCreate:reservation_create_Url,
                reservationDel:reservation_del_Url,
                reservationGet:reservation_get_Url,
                getBroadcastControls:getBroadcastControlsUrl,
                reservationEdit:reservation_edit_Url,
                setBroadcastControlAllUrl:setBroadcastControlAllUrl,
                setBroadcastControl:setBroadcastControlUrl,
                platSettingsSaveUrl:platSettingsSaveUrl,
                programBroadcastControlUrl:programBroadcastControlUrl,
                redirect: redirectUrl,
                advertModifyUrl:advertModifyUrl,
                directorCreateUrl:directorCreateUrl,
                notifyAlertUrl:notifyAlertUrl,
                getQiPuBaseUrl:getQiPuBaseUrl
            }
        })();

        EpgWeb.ajaxQueue = (function () {
            var entity = this;
            var taskArr = [];
            var batchArr = [];
            var timerId = -1;
            var errorCollectArr = [];
            var afterCompleteArr = [];
            var status = -2;
            var checkComplete = function () {
                switch (status) {
                    case 1:
                        clearInterval(timerId);
                        timerId = -1
                        if (errorCollectArr.length > 0) {
                            var totalError = errorCollectArr.join("\n");
                            errorCollectArr = [];
                            EpgWeb.Plugin.showTips({
                                content: totalError,
                                type: "error"
                            })
                        }
                        status = 2;
                        loadComplete();
                        batchComplete();
                        break;
                    case -1:
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                var ajaxData = obj.ajaxData;
                                $.ajax({
                                    type: ajaxData.type,
                                    url: ajaxData.url,
                                    dataType: ajaxData.dataType,
                                    beforeSend: function (request) {
                                        request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                                    },
                                    data: ajaxData.data,
                                    success: function (data) {
                                        var tempTarget = findTaskByRegName(obj.regName);
                                        if (tempTarget.needRemove == true) {
                                            removeTask(obj.regName);
                                        } else {
                                            tempTarget.responseData = data;
                                        }
                                        if (ajaxData.success != null) {
                                            ajaxData.success(data);
                                        }
                                    },
                                    error: function (data) {
                                        if (ajaxData.error != null) {
                                            ajaxData.error(data);
                                        }
                                        errorCollectArr.push(obj.regName + " 请求失败")
                                        removeTask(obj.regName)
                                    }
                                });
                            }
                        })
                        status = 0;
                        timerId = setInterval(checkComplete, 16);
                        break;
                    case 0:
                        var allComplete = true;
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                allComplete = false;
                                return true;
                            }
                        });
                        if (allComplete) {
                            status = 1;
                        }
                        break;
                }
            }

            var batchComplete = function () {
                var tempArr = batchArr;
                batchArr =[];
                while (tempArr.length > 0) {
                    var batchRequestData = tempArr.pop();
                    batchRequestData.handler({"originalArr": batchRequestData.originalArr,
                            "acceptArr": batchRequestData.acceptMsgArr}
                    );
                }
            }

            var loadComplete = function () {
                console.log("loadComplete over");
                var tempArr = afterCompleteArr;
                afterCompleteArr = [];
                while (tempArr.length > 0) {
                    var excuteFunc = tempArr.shift();
                    excuteFunc.call();
                }
            }

            var push = function (regName, ajaxData, responseData, needRemove){
                if (typeof(needRemove) != "boolean") {
                    needRemove = needRemove == null ? false : true
                }
                taskArr.push({"regName": regName, "ajaxData": ajaxData, "responseData": responseData, "needRemove": needRemove})
            }

            var batchRequest = function (regName, ajaxData, sendDataArr, handler){
                var acceptMsgArr = [];
                var batchRequestData = {"originalArr": sendDataArr, "acceptMsgArr": acceptMsgArr, handler: handler }
                batchArr.push(batchRequestData)
                $.each(sendDataArr, function (index, obj) {
                    taskArr.push(
                        {
                            "regName": regName + "_" + index,
                            "ajaxData": {
                                type: ajaxData.type,
                                url: ajaxData.url,
                                dataType: ajaxData.dataType,
                                data: obj,
                                success: function (data) {
                                    var formatData = null;
                                    if (data != null) {
                                        formatData = {"nodeIndex": index, "operationSuccess": false, "responseData": data, "msg": data.msg};
                                        if (data.code == "A00000") {
                                            formatData.operationSuccess = true;
                                        }
                                    } else {
                                        formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    }
                                    acceptMsgArr.push(formatData)
                                },
                                error: function (data) {
                                    var formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    acceptMsgArr.push(formatData);
                                }
                            },
                            "needRemove": true
                        });
                })
            }

            var startLoad = function(){
                if (status != -2 && status != 2) {
                    return false;
                }
                status = -1;
                console.log(JSON.stringify(taskArr) );
                checkComplete();
                return true;
            }

            var findResponseData = function (regName) {
                var task = findTaskByRegName(regName);
                if (task == null) {
                    return null;
                }
                return task.responseData;
            }
            var removeTask = function (regName) {
                var task = findTaskByRegName(regName);
                if (task != null) {
                    var taskIndex = taskArr.indexOf(task)
                    taskArr.splice(taskIndex, 1);
                }
            }

            var findTaskByRegName = function(regName) {
                if (taskArr.length == 0) {
                    return null;
                }
                var returnTarget = null;
                $.each(taskArr, function (index, obj) {
                    if (obj.regName == regName) {
                        returnTarget = obj;
                        return false;
                    }
                })
                return returnTarget;
            }

            var afterLoadComplete = function (callback) {
                if (typeof(callback) == "function") {
                    afterCompleteArr.push(callback);
                }
            }

            var isRunning = function () {
                return status == 0;
            }

            function getTaskArr(){
                return [].concat(taskArr);
            }

            function getStatus(){
                return status;
            }

            return {
                startLoad:startLoad,
                findResponseData:findResponseData,
                findTaskByRegName:findTaskByRegName,
                batchRequest:batchRequest,
                push:push,
                isRunning:isRunning,
                removeTask:removeTask,
                afterLoadComplete:afterLoadComplete,
                getTaskArr:getTaskArr,
                getStatus:getStatus
            }
        })();
    }
);
define(
    '../epg2/EpgWeb.Util',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Util = $.extend(true, {}, Ancestor.Util, {
            tranDurationFormat: function (duration) {
                var darArr = [];
                darArr.push(duration % 60);
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 60);
                }
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 24);
                }
                duration = ( duration - duration % 24) / 24;
                if (duration > 0) {
                    darArr.push(duration);
                }
                var retValue = "";
                switch (darArr.length) {
                    case 4:
                        retValue = darArr[3] + "天";
                    case 3:
                        retValue += darArr[2] + "时";
                    case 2:
                        retValue += darArr[1] + "分";
                    case 1:
                        retValue += darArr[0] + "秒";
                        break;
                }
                return retValue;
            },
            makeUpRedirect: function (url, method, params, needCookie) {
                var requestData = {url: url, type: method, params: params};
                if (needCookie === true) {
                    requestData.needCookie = true;
                }
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },
            quickDateFormat: function (startTime) {
                return startTime.getFullYear() + "-" +
                    (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                    (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
            },
            bindDateMax: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },
            setZeroTime: function (checkTime) {
                checkTime.setSeconds(0);
                checkTime.setMinutes(0);
                checkTime.setHours(0);
                checkTime.setMilliseconds(0);
            },
            setDayLastTime: function (checkTime) {
                checkTime.setSeconds(59);
                checkTime.setMinutes(59);
                checkTime.setHours(23);
                checkTime.setMilliseconds(0);
            },

            bindDate: function (nameMin, nameMax, plusData) {
                var options1 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                }
                var options2 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                }
                if (plusData != null && plusData.hasOwnProperty("slider")) {
                    options1.controlType = "slider";
                    options2.controlType = "slider";
                }
                $("input[name=" + nameMin + "]").datetimepicker(options1)
                $("input[name=" + nameMax + "]").datetimepicker(options2)
                if (plusData != null) {
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },



            bindDateMin: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                }
            },
            createPageBean: function () {
                return (function () {
                    var source = [];
                    var dataLength = source.length;
                    var rowNum = 10;
                    var total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    var cur = 1;

                    function goToFirst() {
                        return goToUser(1);
                    }

                    function goToLast() {
                        return goToUser(total);
                    }

                    function goToUser(toPage) {
                        if (toPage < 1) toPage = 1;
                        if (toPage > total) toPage = total;
                        cur = toPage;
                        var end = cur * rowNum > dataLength ? dataLength : cur * rowNum;
                        var showData = source.slice((cur - 1) * rowNum, end);
                        return {"total": total, "page": cur, "records": dataLength, "rows": showData};
                    }

                    function getCur() {
                        return goToUser(cur);
                    }

                    function goNext() {
                        return goToUser(cur + 1);
                    }

                    function goPrev() {
                        return goToUser(cur - 1);
                    }

                    function setNewData(newData, newRowNum) {
                        source = newData == null ? [] : newData;
                        if (newRowNum != null && newRowNum > 0) {
                            rowNum = newRowNum;
                        }
                        dataLength = source.length;
                        total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    }

                    function addNewOne(newOne) {
                        source.push(newOne);
                        setNewData(source, rowNum);
                    }

                    function delOne(delOne) {
                        var targetIndex = source.indexOf(delOne);
                        if (targetIndex > -1) {
                            source.splice(targetIndex, 1);
                            setNewData(source, rowNum);
                        }
                    }

                    function getSource() {
                        return [].concat(source);
                    }

                    function findData(keyName, value) {
                        var ret = null;
                        if (value == null || keyName == null) {
                            return null;
                        }
                        $.each(source, function (i, element) {
                            if (element != null && element[keyName] == value) {
                                ret = element;
                                return true;
                            }
                        })
                        return ret;
                    }

                    function sortData(func) {
                        if (typeof( func ) == "function") {
                            source.sort(func);
                        }
                    }

                    return {
                        goToFirst: goToFirst,
                        goToLast: goToLast,
                        goToUser: goToUser,
                        goNext: goNext,
                        goPrev: goPrev,
                        getCur: getCur,
                        setNewData: setNewData,
                        addNewOne: addNewOne,
                        delOne: delOne,
                        getSource: getSource,
                        findData: findData,
                        sortData: sortData
                    }
                })()
            },
            pageBeanPageHandler: function (gridId, pageId, pageBean, pgButton) {
                var retValue = null;
                switch (pgButton) {
                    case "next_" + pageId:
                        retValue = pageBean.goNext()
                        break;
                    case "prev_" + pageId:
                        retValue = pageBean.goPrev()
                        break;
                    case "last_" + pageId:
                        retValue = pageBean.goToLast()
                        break;
                    case "user":
                        retValue = pageBean.goToUser(parseInt($("#gbox_" + gridId + " .ui-pg-input").val()));
                        break;
                    case "first_" + pageId:
                        retValue = pageBean.goToFirst();
                        break;
                }
                return retValue
            },
            transGetParams: function (params) {
                var str = "";
                for (var key in params) {
                    str += key + "=" + params[key] + "&";
                }
                if (str.length > 0) {
                    str = str.substr(0, str.length - 1);
                }
                return str;
            },

            formatDateTimeFormat: function (myDate) {
                var year = myDate.getFullYear();
                var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
                var day = ("0" + myDate.getDate()).slice(-2);
                var h = ("0" + myDate.getHours()).slice(-2);
                var m = ("0" + myDate.getMinutes()).slice(-2);
                var s = ("0" + myDate.getSeconds()).slice(-2);
                return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
            },
            getQueryComponent: function (handlerObj) {
                return {
                    source: null,
                    total: 0,
                    completeNum: 0,
                    handlerObj: handlerObj,
                    doInit: function (newArr) {
                        var self = this;
                        self.source = newArr;
                        self.total = newArr.length;
                        self.completeNum = 0;
                        self.doSubmit();
                    },
                    doSubmit: function () {
                        var self = this;
                        self.doBefore();
                        $.each(self.source, function (i, element) {
                            self.doSingle(element, function () {
                                self.notifyHandler()
                            });
                        })
                    },
                    doBefore: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doBefore")) {
                                self.handlerObj.doBefore();
                            }
                        }
                    },
                    doAfter: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doAfter")) {
                                self.handlerObj.doAfter();
                            }
                        }
                    },
                    doSingle: function (element, notifyHandler) {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doSingle")) {
                                self.handlerObj.doSingle(element, notifyHandler);
                            }
                        }
                    },
                    notifyHandler: function () {
                        var self = this;
                        self.completeNum++;
                        if (self.completeNum == self.total) {
                            self.doAfter();
                        }
                    }
                };
            },
            createWeekManager: function (labelArr) {
                return (function ($labelArr) {
                    var focusStartTime = null;
                    var selectDateTime = null;
                    var weekday = "星期日,星期一,星期二,星期三,星期四,星期五,星期六".split(",");

                    function preWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() - 7 * 86400 * 1000));
                        }
                    }

                    function nextWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() + 7 * 86400 * 1000));
                        }
                    }

                    function updateWeek(startTime) {
                        if (startTime != null) {
                            focusStartTime = startTime;
                        }
                        var tempStartTime = new Date(focusStartTime.getTime());
                        $labelArr.each(function (i, element) {
                            var lDateFormat = EpgWeb.Util.quickDateFormat(tempStartTime);
                            $(element).attr("query-date", lDateFormat);
                            $(element).removeClass("selected");
                            $(element).html(weekday[tempStartTime.getDay()] + "<br>" + lDateFormat);
                            if (lDateFormat == selectDateTime) {
                                $(element).addClass("selected");
                            }
                            tempStartTime.setTime(tempStartTime.getTime() + 86400 * 1000);
                        })
                    }

                    function quickToCurrentWeek() {
                        var current = new Date();
                        var currentIndex = -1;
                        if (current.getDay() == 0) {
                            currentIndex = 6;
                        } else {
                            currentIndex = current.getDay() - 1;
                        }
                        selectDateTime = EpgWeb.Util.quickDateFormat(current)
                        updateWeek(new Date(current.getTime() - currentIndex * 86400 * 1000));
                        //updateTableByDate(selectDateTime);
                        return selectDateTime;
                    }

                    return{
                        preWeek: preWeek,
                        nextWeek: nextWeek,
                        quickToCurrentWeek: quickToCurrentWeek
                    }
                })(labelArr)
            },
            createHeartBeatUtil: function () {
                return  (function () {
                    var params = {
                        startTime: 0,
                        isStarted: false,
                        indexId: 0,
                        dataArr: []
                    }

                    function doHeartBeat() {
                        var curTime = Date.now();
                        var cpArr = [].concat(params.dataArr);

                        $.each(cpArr, function (i, element) {
                            tick(element, curTime);
                        })
                    }

                    function start() {
                        if (params.isStarted) {
                            console.log("has started");
                            return;
                        }
                        params.startTime = Date.now();
                        params.isStarted = true;
                        $.each(params.dataArr, function (i, elment) {
                            elment.lastTime = params.startTime;
                        })
                        setInterval(function () {
                            doHeartBeat();
                        }, 160)
                    }

                    function tick(element, curTime) {
                        if (element.block || element.stop) {
                            return;
                        }
                        if (element.lastTime + element.gapTime < curTime) {
                            element.lastTime = curTime;
                            element.options.handler();
                            if (element.options.needBlock) {
                                element.block = true;
                            }
                        }
                    }

                    function pushTask(taskObj) {
                        params.indexId++;
                        var taskOptions = {
                            block: false,
                            stop: taskObj.stop || false,
                            options: taskObj,
                            id: params.indexId,
                            lastTime: 0
                        }
                        taskOptions.gapTime = accountGapTime(taskObj)
                        if (params.isStarted) {
                            taskOptions.lastTime = Date.now() + 100;
                        }
                        params.dataArr.push(taskOptions);
                        return taskOptions;
                    }

                    function accountGapTime(taskObj) {
                        var time = [0, 0, 0, 0];//ms,s,m,h
                        if ("ms" in taskObj.gap) {
                            time[0] = taskObj.gap.ms;
                        }
                        if ("s" in taskObj.gap) {
                            time[1] = taskObj.gap.s;
                        }
                        if ("m" in taskObj.gap) {
                            time[2] = taskObj.gap.m;
                        }
                        if ("h" in taskObj.gap) {
                            time[3] = taskObj.gap.h;
                        }
                        return  time[0] + time[1] * 1000 + time[2] * 60000 + time[3] * 3600000;
                    }

                    return {
                        start: start,
                        doHeartBeat: doHeartBeat,
                        pushTask: pushTask,
                        tick: tick
                    }
                })();
            },
            notifyAlert: function (sendData, handler) {
                EpgWeb.Dao.notifyAlert(sendData, function (rdata) {
                    handler(rdata)
                });
            },
            getCurrentUserEntity:function(){
                var ret = null;
                try{
                    ret =auth.baseInfo.authInfo;
                }catch (e){
                    console.warn(e);
                }
                return ret
            }
        });
    }
);
define(
    '../epg2/EpgWeb.Plugin',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Plugin = {
            showTips: function (options) {
                if (!options.hasOwnProperty("type")) {
                    options.type = "success";
                }
                if ($(document).tips != null) {
                    $(document).tips(options)
                }
                if ($(document).tip != null) {
                    $(document).tip(options)
                } else {
                    console.log("no tips plugin " + options);
                }
            },
            Validate: (function () {
                var reg1 = /^\d+$/;
                var reg3 = /^[1-9]\d*$/;
                var reg2 = /^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) ([0-2][0-9]):([0-5][0-9]):([0-5][0-9])$/;
                var reg4 = /^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
//                var _defaultHandler = function(msg){
//                    EpgWeb.Plugin.showTips({type: "error", content: msg})
//                }
                var _bindHandler = null;
                var checkObj = {
                    self_design: function (checkData, checkValue) {
                        return checkData.checkCall(checkData, checkValue)
                    },
                    date: function (checkData, checkValue) {
                        return checkDateFormat(checkValue);
                    },
                    not_empty: function (checkData, checkValue) {
                        return checkValue != null && $.trim(checkValue).length > 0;
                    },
                    eq: function (checkData, checkValue) {
                        return checkValue === checkData.other;
                    },
                    ne: function (checkData, checkValue) {
                        return checkValue !== checkData.other;
                    },
                    ge: function (checkData, checkValue) {
                        return  checkValue >= checkData.other;
                    },
                    gt: function (checkData, checkValue) {
                        return  checkValue > checkData.other;
                    },
                    lt: function (checkData, checkValue) {
                        return checkValue < checkData.other;
                    },
                    le: function (checkData, checkValue) {
                        return checkValue <= checkData.other;
                    },
                    positive:function(checkData, checkValue) {
                        return  checkPositive(checkValue)
                    },
                    number: function (checkData, checkValue) {
                        return checkNum(checkValue);
                    },
                    endsWith: function (checkData, checkValue) {
                        return checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                    }
                }

                function checkNum(checkString) {
                    return reg1.test(checkString)
                }

                function checkDateFormat(checkString) {
                    return reg2.test(checkString)
                }

                function checkPositive(checkString) {
                    return reg3.test(checkString)
                }

                function defaultHandler(msg) {
                    if(_bindHandler != null){
                        _bindHandler(msg);
                    }
                }

                function batchCheck(checkArr) {
                    if (checkArr == null) {
                        checkArr = [];
                    }
                    if (checkArr.length == 0) {
                        return true;
                    }
                    var flag = false;
                    $.each(checkArr, function (index, checkData) {
                        flag = baseCheck(checkData);
                        if (!flag) {
                            return false;
                        }
                    })
                    return flag;
                }

                function baseCheck(checkData) {
                    var flag = false;
                    //$.isArray(checkData.value )
                    if (!(checkData.value instanceof Array)) {
                        checkData.value = [checkData.value];
                    }
                    //$.isArray(checkData.error )
                    if (!(checkData.error instanceof Array)) {
                        checkData.error = [checkData.error];
                    }
                    if (checkData.handler == null) {
                        checkData.handler = defaultHandler;
                    }
                    $.each(checkData.value, function (index, checkValue) {
                        if (checkObj.hasOwnProperty(checkData.type)) {
                            flag = checkObj[checkData.type](checkData, checkValue);
                        }
                        if (!flag) {
                            var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                            checkData.handler(hint);
                            return false;
                        }
                    })
                    return flag
                }
                function bindDefaultHandler(func){
                    _bindHandler = func;
                }
                return {
                    baseCheck: baseCheck,
                    batchCheck: batchCheck,
                    checkDateFormat: checkDateFormat,
                    checkNum: checkNum,
                    bindDefaultHandler:bindDefaultHandler
                }
            })(),

            tableToExcel: (function () {
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) {
                        return window.btoa(unescape(encodeURIComponent(s)))
                    },
                    format = function (s, c) {
                        return s.replace(/{(\w+)}/g,
                            function (m, p) {
                                return c[p];
                            })
                    };

                return function (table, name) {
                    if (!table.nodeType) table = document.getElementById(table)
                    var ctx = {
                        worksheet: name || 'Worksheet',
                        table: table.innerHTML
                    }
                    window.location.href = uri + base64(format(template, ctx))
                }
            })()
        };

    }
);
define(
    '../epg2/EpgWeb.Dao',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Dao = $.extend({}, Ancestor.Dao, {
            cfgName: {
                LiveType: "LiveType",
                LogType: "LogType",
                episodeGradeType: "EpisodeGradeType",
                liveProgramType: "LiveProgramType",
                liveChannelType: "LiveChannelType",
                getChannel: "getChannel"
            },
            channelId: null,
            getDataByName: function (targetName) {
                var responseData = EpgWeb.ajaxQueue.findResponseData(targetName);
                return responseData;
            },
            sendAjax: function (url, method, data, callback, authUrl) {
                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    type: method,
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                };
                Ancestor.Dao.ajax(options, authUrl);
            },
            appendAuthUrl: function (options, authUrl) {
                options = $.extend({},options, {
                    beforeSend: function (request) {
                        var authBase = Ancestor.Util.getAuth('/vod/episodeLogList');
                        request.setRequestHeader('Sign', authBase.sign);
                        request.setRequestHeader("Time", authBase.clientTime);
                        request.setRequestHeader("From", authBase.from);
                        request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                    }
                })
                return options;
            },

            sendProxy: function (options, headers) {
                $.ajax(this.transToProxyOptions(options, headers));
            },
            transToProxyOptions: function (options, headers) {
                var requestData = {url: options.url, type: options.type, params: options.data, needCookie: true};
                if (headers != null) {
                    requestData.headers = headers;
                }
                var newOptions = {
                    url: EpgWeb.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    timeout: options.timeout?options.timeout: 5000,
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        options.success(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        options.error(null);
                    }
                }
                return newOptions;
            },
            doGet: function (url, data, callback) {
                var dataArr = [];
                for (var key in data) {
                    dataArr.push(key + "=" + data[key]);
                }

                var options = {
                    url: url,
                    dataType: 'json',
                    data: dataArr.join("&"),
                    type: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                $.ajax(options);
            },
            doAuthData: function (handlerObj) {
                if (auth == null) {
                    auth = Ancestor.Auth;
                }
                auth.getAuthData({tips: 1, url: handlerObj.url}, function (rt) {
                    if (rt == null) {
                        if (handlerObj.hasOwnProperty("doSuccess")) {
                            handlerObj.doSuccess();
                        }
                    } else {
                        if (handlerObj.hasOwnProperty("doError")) {
                            handlerObj.doError();
                        }
                    }
                    if (handlerObj.hasOwnProperty("doFinal")) {
                        handlerObj.doFinal();
                    }
                });
            },
//            checkJSVersion: function (data, callback) {
//                //method, data, callback, authUrl) {
//                this.sendAjax("/api/version/check", "post", {data:JSON.stringify(data)}, callback);
//            }
            notifyAlert: function (sendData, callback) {
                var url = EpgWeb.urlConfig.notifyAlertUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(sendData)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/notify/alertPlatform");
            }

        })
    }
);
define(
    '../epg2/EpgWeb.Task',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Task = (function () {
            var handler = function(data,callback){
                if (callback != null) {
                    callback.call(this, data);
                }
            }
            var getConfigType = function (typeName, callback, regName) {
                if (regName == null) {
                    regName = typeName;
                }
                return {
                    regName: regName,
                    options: {
                        type: "get",
                        url: EpgWeb.urlConfig.configs,
                        dataType: "json",
                        data: {type: typeName},
                        success: function(data){
                            handler.call(this, data,callback);
                        },
                        error: function(data){
                            handler.call(this, data,callback);
                        }
                    }
                }
            }

            var getChannel = function (regName,params) {
                return {
                    regName:regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.channelGet,
                        dataType: "json",
                        data: params
                    }
                }
            }
            return {
                getConfigType: getConfigType,
                getChannel:getChannel
            }
        })()
    }
);
define(
    '../record/Record',['require','exports','module'],function (require, exports, module) {
        window.Record = window.Record || { version: '1.0' };
        Record.Constant = {
            baseApiUrl: "/api/",
            devMode: auth.dev(),
            thirdUrl_query_user: "http://lego.iqiyi.com/external/auth/auth-api/services/user/search",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list"
        }
        Record.urlConfig = (function () {
            var useUrl = Record.Constant.baseApiUrl;
            var redirectUrl = useUrl + "redirect";
            var getPlanLibraryListUrl = useUrl + "record/plan/libraryList";
            var doPlanSaveUrl = useUrl + "record/plan/save";
            var doPlanEditUrl = useUrl + "record/plan/edit";
            var doPlanDelUrl = useUrl + "record/plan/del";
            var getRecordChannelUrl = useUrl + "record/channel/list";
            var getRecordColUrl = useUrl + "record/col/list";
            var getPlanByIdUrl = useUrl + "record/plan/getById";
            var getTaskLibraryListUrl = useUrl + "record/task/libraryList";
            var doTaskEditUrl = useUrl + "record/task/edit";
            var doChannelAddUrl = useUrl + "record/channel/save";
            var doChannelEditUrl = useUrl + "record/channel/edit";
            var doChannelDelUrl = useUrl + "record/channel/del";
            //信号管理
            var getSignalLibraryListUrl = useUrl + "record/signal/libraryList";
            var doSignalSaveUrl = useUrl + "record/signal/save";
            var doSignalDelUrl = useUrl + "record/signal/del";
            var doSignalEditUrl = useUrl + "record/signal/edit";
            var doSignalGetByIdUrl = useUrl + "record/signal/getById";

            //关联信号
            var getChannelSignalLibraryListUrl = useUrl + "record/channel/signal/libraryList";
            var doChannelSignalSaveUrl = useUrl + "record/channel/signal/save";
            var doChannelSignalDelUrl = useUrl + "record/channel/signal/del";
            var doChannelSignalEditUrl = useUrl + "record/channel/signal/edit";
            var doChannelSignalGetByIdUrl = useUrl + "record/channel/signal/getById";
            var doChannelSignalStartUrl = useUrl + "record/channel/signal/start";
            var doChannelSignalStopUrl = useUrl + "record/channel/signal/stop";


            var doChannelSignalTableUrl = useUrl + "record/channelSignal/tableList";

            return {
                redirectUrl: redirectUrl,
                getPlanLibraryListUrl: getPlanLibraryListUrl,
                doPlanSaveUrl: doPlanSaveUrl,
                doPlanEditUrl: doPlanEditUrl,
                doPlanDelUrl: doPlanDelUrl,
                getPlanByIdUrl: getPlanByIdUrl,
                getRecordChannelUrl:getRecordChannelUrl,
                getRecordColUrl:getRecordColUrl,
                getTaskLibraryListUrl:getTaskLibraryListUrl,
                doTaskEditUrl:doTaskEditUrl,
                doChannelAddUrl:doChannelAddUrl,
                doChannelEditUrl:doChannelEditUrl,
                doChannelDelUrl:doChannelDelUrl,
                getSignalLibraryListUrl:getSignalLibraryListUrl,
                doSignalSaveUrl:doSignalSaveUrl,
                doSignalDelUrl:doSignalDelUrl,
                doSignalEditUrl:doSignalEditUrl,
                doSignalGetByIdUrl:doSignalGetByIdUrl,

                getChannelSignalLibraryListUrl:getChannelSignalLibraryListUrl,
                doChannelSignalSaveUrl:doChannelSignalSaveUrl,
                doChannelSignalDelUrl:doChannelSignalDelUrl,
                doChannelSignalEditUrl:doChannelSignalEditUrl,
                doChannelSignalGetByIdUrl:doChannelSignalGetByIdUrl,
                doChannelSignalStartUrl:doChannelSignalStartUrl,
                doChannelSignalStopUrl:doChannelSignalStopUrl,
                doChannelSignalGetByIdUrl:doChannelSignalGetByIdUrl,
                doSignalGetByIdUrl:doSignalGetByIdUrl,
                doChannelSignalTableUrl:doChannelSignalTableUrl
            }
        })()
    }
);
define(
    '../record/Record.PlanGrid',['require','exports','module'],function (require, exports, module) {

        Record.PlanGrid = function (options) {
            this.dao = Record.Dao;
            this.config = Record.Config;
            this.util = Record.Util;
            this.task = Record.Task;
            this.options = options || {};
        };

        Com.inherits(Record.PlanGrid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;
                var taskArr = [];
                taskArr.push(self.task.getLegoCategory("lego_category"))
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.bindEvent();
                    self.initDateTimePicker();
                    self.initSuggest();
                    self.initGrid();
                    self.initSelect();
                    self.initDlg();
                    self.initFirstQuery();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            initFirstQuery: function () {
                $("#belong_channel_div").hide();
                try {
                    var channelId = Com.url.getParameter("channel_id");
                    if (channelId != null && !isNaN(channelId)) {
                        $("input[name='EQL_channel.id']").val(channelId);
                    } else {
                        $("#belong_channel_div").show();
                    }
                } catch (e) {
                    console.log("initFirstQuery error");
                }
                var self = this;
                self.query();
            },
            bindEvent: function () {
                var self = this;
                $("button[name=open_new_dlg_btn]").bind("click", function (event) {
                    var channelId = Com.url.getParameter("channel_id");
                    if (channelId != null && !isNaN(channelId)) {
                        Record.Util.openPlanModifyDlg(parseInt(channelId),1);
                    } else {
                        Record.Util.openPlanModifyDlg(-1);
                    }
                })

                $("button[name=query_btn]").bind("click", function (event) {
                    self.query();
                })
                $(".query-chosen-select").chosen({width: "300px"});
                $(".chosen-select").chosen({width: "300px"});

                $("select[name='EQI_recordPlan.play_type']").bind("change", function (event) {
                    if ($(event.currentTarget).val() == 1) {
                        $("#record-plan-repeat-div").show();
                    } else {
                        $("#record-plan-repeat-div").hide();
                    }
                })
            },
            initDateTimePicker: function () {
                EpgWeb.Util.bindDate("'GES_recordPlan.create_time'", "'LES_recordPlan.create_time'");
                var now = new Date();
                $('input[name="start_date"]').datepicker({
                    yearRange: '2010:C+5',
                    addSliderAccess: true,
                    minDate : now,
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $('input[name="stop_date"]').datepicker("option", "minDate", selectedDate);
                    }
                });
                $('input[name="stop_date"]').datepicker({
                    yearRange: '2010:C+5',
                    addSliderAccess: true,
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $('input[name="start_date"]').datepicker("option", "maxDate", selectedDate);
                    }
                });
                $('input[name="start_day_time"]').timepicker({
                    yearRange: '2010:C+5',
                    addSliderAccess: true,
                    minTime: now,
                    sliderAccessArgs: { touchonly: false }
                });
                $('input[name="stop_day_time"]').timepicker({
                    yearRange: '2010:C+5',
                    addSliderAccess: true,
                    sliderAccessArgs: { touchonly: false }
                });
            },

             initSuggest: function () {
                 var self = this;
                var channelSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/record/channel/list");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        select: function (event, object) {
                            var obj = { "EQL_channelId": Number(object.item.id) };
                            Record.Dao.getColList({paramsObj: JSON.stringify(obj), dataMode: "simple", pageSize: 100}, function (retData) {
                                Record.Util.fillRelationColSelect(retData);
                            })
                            return true;
                        },
                        source: Record.urlConfig.getRecordChannelUrl,
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var jsonObj = { LIKES_channelName: $.trim(term) };
                            return { "dataMode": "simple", paramsObj: JSON.stringify(jsonObj) }
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["channelName"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }

                $("input[name=channel_name]").suggest(channelSuggest.options);

                var emailSuggest = {
                    options: {
                        source: Record.urlConfig.redirectUrl,
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: Record.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["email"];
                                itemData[options.labelKey] = item["userName"]
                                itemData["value"] = item["userName"];
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label + "(" + item.id + ")";
                        }
                    }
                }
                $("input[name=project_workers]").suggest(emailSuggest.options);

            },
            initGrid: function (options) {
                var self = this;
                self.$grid = self.options.$grid;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.PLAN_DATA_LIST);
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);
            },
            query: function (callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            getParam: function () {
                var params = {};
                var inputArr = $('form[role="queryForm"]').find("input[role=query-text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("name")] = element.value.trim()
                    }
                })
                var selectArr = $('form[role="queryForm"]').find("select[role=query-select]")
                $.each(selectArr, function (i, element) {
                    if (element.name != "query-repeat-code") {
                        if (element.value.trim().length > 0) {
                            params [$(element).attr("name")] = element.value.trim()
                        }
                    }
                })
                if ($("select[name=query-repeat-code]").is(":visible")) {
                    var repeatCodeArr = $("select[name=query-repeat-code]").val();
                    if (repeatCodeArr != null) {
                        var repeatCodeValue = 0;
                        $.each(repeatCodeArr, function (i, codeValue) {
                            repeatCodeValue = repeatCodeValue | parseInt(codeValue);
                        })
                        params["EQL_recordPlan.repeat_code&" + repeatCodeValue] = repeatCodeValue;
                    }
                }
                params["EQI_recordPlan.status"] = 1;
                console.log("params:" + JSON.stringify(params));

                return { paramsObj: JSON.stringify(params) };
            },
            initSelect: function () {
                var resultData = Record.Dao.getDataByName("lego_category");
                var filterArr = [];
                $.each(resultData.data, function (i, element) {
                    filterArr.push({ key: element.id, val: element.name})
                })
                var selectJDom = $("select[name='EQI_col.category_id']");
                $("<option value=''>全部</option>").appendTo(selectJDom);
                $.each(filterArr, function (index, obj) {
                    $("<option>", {
                        value: obj.key,
                        html: obj.val
                    }).appendTo(selectJDom);
                });
            },
            initDlg: function () {
                var self = this;
                self.initAddFormDlg();
            },

            initAddFormDlg: function () {
                $("form[role=addForm]").dialog({
                    title: "新建计划",
                    autoOpen: false,
                    height: 640,
                    width: 840,
                    modal: true
                })
                $("button[name=add_plan_btn]").bind("click", function (event) {
                    Record.Util.sendAddRecordPlan();
                })
                $("button[name=edit_plan_btn]").bind("click", function (event) {
                    Record.Util.sendEditRecordPlan();
                })
                $("button[name=cancel_btn]").bind("click", function (event) {
                    $("form[role=addForm]").dialog("close")
                })
                $("input[name=plan_type]").bind("click", function (event) {
                    var value = $(event.currentTarget).val();
                    if (value == 1) {
                        $("#range_time_div").show();
                        $("#repeat_code_div").show();
                        $("#fragment_output_div").hide();
                    } else if (value == 2) {
                        $("#range_time_div").hide();
                        $("#repeat_code_div").hide();
                        $("#fragment_output_div").show();
                    }
                })

                $("select[name=enable]").on('change',function (event) {
                    var parentDom = $("form[role=addForm]");
                    if($(this).attr('status') && $(this).attr('status')== 1 && $(this).val()==1){
                        parentDom.find('input').each(function(i,ele){
                            $(ele).attr('disabled','disabled');

                        });
                        parentDom.find('select[name="col_name"]').attr('disabled','disabled');
                        parentDom.find(".chosen-select").prop('disabled', true).trigger("chosen:updated");
                        parentDom.find(".qui-tag-remove").each(function(i,ele){
                            $(ele).hide();
                        });
                    }else{
                        parentDom.find('input').each(function(i,ele){
                            if( $(ele).attr('name')!= 'channel_name' ){
                                $(ele).attr('disabled',false);
                            }
                        });
                        parentDom.find('select[name="col_name"]').attr('disabled',false);
                        parentDom.find(".chosen-select").prop('disabled', false).trigger("chosen:updated");
                        parentDom.find(".qui-tag-remove").each(function(i,ele){
                            $(ele).show();
                        });
                    }
                })
            }
        });

    }
);
define(
    '../record/Record.TaskGrid',['require','exports','module'],function (require, exports, module) {

        Record.TaskGrid = function (options) {
            this.dao = Record.Dao;
            this.config = Record.Config;
            this.util = Record.Util;
            this.task = Record.Task;
            this.options = options || {};
        };

        Com.inherits(Record.TaskGrid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;
                var taskArr = [];
                taskArr.push(self.task.getLegoCategory("lego_category"))
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.bindEvent();
                    self.initDateTimePicker();
                    self.initSelect();
                    self.initGrid();
                    self.initFirstQuery();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            initFirstQuery: function () {
                $("#belong_channel_div").hide();
                try {
                    var channelId = Com.url.getParameter("channel_id");
                    if (channelId != null && !isNaN(channelId)) {
                        $("input[name='EQL_channel.id']").val(channelId);
                    } else {
                        $("#belong_channel_div").show();
                    }
                } catch (e) {
                    console.log("initFirstQuery error");
                }
                var self = this;
                self.query();
            },
            bindEvent: function () {
                var self = this;
                $("button[name=query_btn]").bind("click", function (event) {
                    self.query();
                })
            },
            initDateTimePicker: function () {
                EpgWeb.Util.bindDate("'GES_record_task.task_start_time'", "'LES_record_task.task_start_time'");
            },
            initSelect: function () {
                var resultData = Record.Dao.getDataByName("lego_category");
                var filterArr = [];
                $.each(resultData.data, function (i, element) {
                    filterArr.push({ key: element.id, val: element.name})
                })
                var selectJDom = $("select[name='EQI_col.category_id']");
                $("<option value=''>全部</option>").appendTo(selectJDom);
                $.each(filterArr, function (index, obj) {
                    $("<option>", {
                        value: obj.key,
                        html: obj.val
                    }).appendTo(selectJDom);
                });

                var taskStatusDom = $("select[name='EQI_record_task.task_status']");
                $("<option value=''>全部</option>").appendTo(taskStatusDom);
                for (var key in Record.Config.TASK_STATUS_TAB) {
                    $("<option>", {
                        value: key.replace("key", ""),
                        html: Record.Config.TASK_STATUS_TAB[key]
                    }).appendTo(taskStatusDom);
                }
                ;
            },
            initGrid: function (options) {
                var self = this;
                self.$grid = self.options.$grid;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TASK_DATA_LIST);
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);
            },
            query: function (callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            getParam: function () {
                var params = {};
                var inputArr = $('form[role="queryForm"]').find("input[role=query-text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("name")] = element.value.trim()
                    }
                })
                var selectArr = $('form[role="queryForm"]').find("select[role=query-select]")
                $.each(selectArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("name")] = element.value.trim()
                    }
                })
                params["EQI_record_task.status"] = 1;
                console.log("params:" + JSON.stringify(params));
                return { paramsObj: JSON.stringify(params) };
            }
        });

    }
);
define('../record/Record.Config',['require','exports','module'],function (require, exports, module) {

    Record.Config = $.extend({}, {}, {
        TABLE_COLMODEL_CONFIG: {
            id: {
                name: "id",
                index: 'id',
                title: false,
                width: 80,
                align: "left",
                sortable: false
            },
            planId: {
                name: "planId",
                index: 'planId',
                title: false,
                width: 100,
                align: "left",
                sortable: false
            },
            colName: {
                name: "colName",
                index: 'colName',
                title: false,
                width: 120,
                align: "left",
                sortable: false
            },
            channelName: {
                name: "channelName",
                index: 'channelName',
                title: false,
                width: 120,
                align: "left",
                sortable: false
            },
            category: {
                name: "categoryId",
                index: 'categoryId',
                title: false,
                width: 100,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.category(v, o, r);
                }
            },
            hasAuth: {
                name: "hasAuth",
                index: 'hasAuth',
                title: false,
                width: 80,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.hasAuth(v, o, r);
                }
            },

            planType: {
                name: "planType",
                index: 'planType',
                title: false,
                width: 100,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.planType(v, o, r);
                }
            },
            planRule: {
                title: false,
                width: 250,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.planRule(v, o, r);
                }
            },
            enable: {
                name: "enable",
                index: 'enable',
                title: false,
                width: 80,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.enable(v, o, r);
                }
            },
            opUser: {
                name: "opUser",
                index: 'opUser',
                title: false,
                width: 180,
                align: "left",
                sortable: false
            },
            addTime: {
                name: "createTime",
                index: 'createTime',
                title: false,
                width: 150,
                align: "left",
                sortable: false
            },
            operator_plan_list: {
                title: false,
                width: 100,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.operator_plan_list(v, o, r);
                }
            },
            operator_task_list: {
                title: false,
                width: 100,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.operator_task_list(v, o, r);
                }
            },
            taskStatus: {
                name: "taskStatus",
                index: 'taskStatus',
                title: false,
                width: 100,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.taskStatus(v, o, r);
                }
            },
            elementName: {
                title: false,
                width: 200,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.elementName(v, o, r);
                }
            },
            task_range_time:{
                title: false,
                width: 150,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.task_range_time(v, o, r);
                }
            },
            channelName:{
                name: "channelName",
                index: 'channelName',
                title: false,
                width: 150,
                align: "left",
                sortable: false
            },
            channelCode:{
                name: "channelCode",
                index: 'channelCode',
                title: false,
                width: 150,
                align: "left",
                sortable: false
            },
            createTime: {
                name: "createTime",
                index: 'createTime',
                title: false,
                width: 200,
                align: "left",
                sortable: false
            },
            operator_channel_list: {
                title: false,
                width: 500,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.operator_channel_list(v, o, r);
                }
            },
            hasCaption: {
                name: "hasCaption",
                index: 'hasCaption',
                title: false,
                width: 100,
                align: "left",
                sortable: false,
                formatter: function(v, o, r) {
                    return Record.Util.formatter.hasCaption(v, r);
                }
            },
            videoName:{
                name: "videoName",
                index: 'videoName',
                title: false,
                width: 150,
                align: "left",
                sortable: false
            },
            recordTime:{
                name: "recordTime",
                index: 'recordTime',
                title: false,
                width: 150,
                align: "left",
                sortable: false
            },
            videoStatus:{
                name: "videoStatus",
                index: 'videoStatus',
                title: false,
                width: 100,
                align: "left",
                sortable: false,
                formatter: function(v, o, r) {
                    return Record.Util.formatter.videoStatus(v, r);
                }
            },
            recordVideoId: {
                name: "recordVideoId",
                index: 'recordVideoId',
                title: false,
                width: 100,
                align: "left",
                hidden: true
            },
            videoId: {
                name: "videoId",
                index: 'videoId',
                title: false,
                width: 100,
                align: "left",
                sortable: false,
            },
            taskId: {
                name: "taskId",
                index: 'taskId',
                title: false,
                width: 100,
                align: "left",
                hidden: true
            },
            serverIp: {
                name: "serverIp",
                index: 'serverIp',
                title: false,
                width: 100,
                align: "left",
                hidden: true
            },

            operator_channelSignalTable_list:{
                title: false,
                width: 100,
                align: "left",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Util.formatter.operator_channelSignalTable_list(v, o, r);
                }
            }
        },
        PLAN_DATA_LIST: {
            url: Record.urlConfig.getPlanLibraryListUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/record/plan/libraryList");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 20,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["计划ID", "栏目名称", "频道", "素材分类", "有无版权", "执行方式", "执行规则", "开启状态", "创建人", "创建时间", "操作"],
            colModel: ['id', "colName" , "channelName", "category", "hasAuth", "planType", "planRule" , "enable" , "opUser", "addTime", "operator_plan_list"],
            pager: "#pager"
        },


        TASK_DATA_LIST: {
            url: Record.urlConfig.getTaskLibraryListUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/record/task/libraryList");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 20,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["任务ID", "计划ID", "栏目名称", "素材名称","频道", "素材分类", "有无版权", "状态", "任务起止时间", "操作"],
            colModel: ['id', "planId", "colName", "elementName","channelName", "category", "hasAuth", "taskStatus", "task_range_time", "operator_task_list"],
            pager: "#pager"
        },

        CHANNEL_DATA_LIST: {
            url: Record.urlConfig.getRecordChannelUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/record/channel/list");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 20,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["频道ID", "频道名称", "频道代码","是否有台标", "创建人", "创建时间", "操作"],
            colModel: ['id', "channelName", "channelCode", "hasCaption", "opUser", "createTime", "operator_channel_list"],
            pager: "#pager"
        },

        CHANNELSIGNALTABLE_DATA_LIST: {
            url: Record.urlConfig.doChannelSignalTableUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/record/channelSignal/tableList");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 20,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["收录服务器IP", "任务ID", "收录视频ID", "视频ID", "素材名称", "栏目名称", "收录时间", "频道", "素材分类", "有无版权", "状态", "创建人", "创建时间", "操作"],
            colModel: ["serverIp", "taskId", "recordVideoId", "videoId", "videoName", "colName", "recordTime", "channelName", "category", "hasAuth", "videoStatus", "opUser", "createTime", "operator_channelSignalTable_list"],
            pager: "#pager"
        },

        CODE_SUC: "A00000",
        REPEAT_CODE_ARR: [  4 , 8 , 16, 32, 64 , 128 , 2],
        REPEAT_CODE_CH_ARR: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        TASK_STATUS_TAB: {
            key1: "通知收录成功", key2: "通知收录失败",
            key100: "待收录", key101: "任务开始失败",
            key200: "任务开始执行", key201: "任务开始失败", key202: "任务开始上传", key203: "任务上传失败",
            key300: "视频合并中", key302: "视频合并失败",
            key401: "任务取消", key500: "入待审库",
            key501: "打点提交", key502: "打点失败",key600: "上传"
        },
        TASK_STATUS_ENUM_VALUE: {
            WAIT: 100, START_FAIL: 101, START_OVERTIME: 102, IN_RECORD: 200, RECORD_FAIL: 201, VIDEO_MERGE: 300, VIDEO_MERGE_OVERTIME: 302,
            TASK_CANCEL: 401, ENTER_LIBRARY: 500
        },
        CHANNEL_HASCAPTION_ARR: ["否", "是"],
        VIDEO_STATUS: {"100":"待审核打点", "200":"收录中", "201":"收录失败", "300":"已入素材库", "301":"入素材库失败", "400":"废弃"}
    });
});
define('../record/Record.Util',['require','exports','module'],function (require, exports, module) {
    Record.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            operator_plan_list: function (v, o, r) {
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='Record.Util.openPlanModifyDlg(" + r.id + ")'>修改</a>");
                if (r.enable == 1) {
                    htmlArr.push("<a class='disabled'>删除</a> ");
                } else {
                    htmlArr.push("<a href='javascript:;' onclick='Record.Util.delPlan(" + r.id + ")'>删除</a>");
                }
                return htmlArr.join("&nbsp;");
            },
            category: function (v, o, r) {
                var resultData = Record.Dao.getDataByName("lego_category");
                var ret = "";
                $.each(resultData.data, function (i, element) {
                    if (element.id == v) {
                        ret = element.name;
                        return false;
                    }
                })
                return ret;
            },
            hasAuth: function (v, o, r) {
                return v == 1 ? "有" : "无";
            },
            enable: function (v, o, r) {
                return v == 1 ? "启用" : "禁用";
            },
            planType: function (v, o, r) {
                var ret = "未设定";
                switch (v) {
                    case 1 :
                        ret = "循环输出";
                        break;
                    case 2:
                        ret = "全时输出";
                        break;
                }
                return ret;
            },
            planRule: function (v, o, r) {
                var retArr = [];
                if (r.planType == 1) {
                    retArr.push("重复周期:" + Record.Util.decodeRepeatCode(r.repeatCode, "ch") + "<br>");
                    retArr.push("收录日期:" + r.startDate + "至" + r.stopDate + "<br>");
                    retArr.push("收录时间:" + r.startDayTime + "至" + r.stopDayTime + "<br>");
                } else if (r.planType == 2) {
                    retArr.push("收录日期:" + r.startDate + "至" + r.stopDate + "<br>");
                    retArr.push("分段时间:" + r.fragmentOutput + "分钟<br>");
                }
                return retArr.join("");
            },
            operator_task_list: function (v, o, r) {
                var htmlArr = [];
                if (r.taskStatus == Record.Config.TASK_STATUS_ENUM_VALUE.WAIT) {
                    htmlArr.push("<a href='javascript:;' onclick='Record.Util.changeTaskStatus(" + r.id + ")'>取消</a>");
                }
                return htmlArr.join();
            },
            taskStatus: function (v, o, r) {
                var ret = Record.Config.TASK_STATUS_TAB["key" + v];
                if (ret == null) {
                    return "";
                }
                return ret;
            },
            elementName: function (v, o, r) {
                return r.colName + "_" + r.taskStartTime.replace(/[-: ]/g, "").substring(0, 12);
            },
            operator_channel_list: function (v, o, r) {
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='Record.Util.openChannelModifyDlg(" + r.id + ")'>修改</a>");
                htmlArr.push("<a href='javascript:;' onclick='Record.Util.delChannel(" + r.id + ")'>删除</a>");
                htmlArr.push("<a href='http://zzd.lego.iqiyi.com/epg/record_channel_signal.html?channel_id=" + r.id + "' target='_blank' onclick=''>信号关联</a>");
                htmlArr.push("<a href='http://zzd.lego.iqiyi.com/epg/recordcol.html?channel_id=" + r.id + "&channel_name=" + encodeURI(r.channelName) + "' target='_blank'>栏目列表</a>");
                htmlArr.push("<a href='http://zzd.lego.iqiyi.com/epg/record_plan.html?channel_id=" + r.id + "&channel_name=" + encodeURI(r.channelName) + "' target='_blank'>计划列表</a>");
                htmlArr.push("<a href='http://zzd.lego.iqiyi.com/epg/record_task.html?channel_id=" + r.id + "&channel_name=" + encodeURI(r.channelName) + "' target='_blank'>任务列表</a>");
                return htmlArr.join("&nbsp;");
            },
            task_range_time: function (v, o, r) {
                return r.taskStartTime + "\n" + r.taskStopTime;
            },
            hasCaption: function (v, r) {
                return Record.Config.CHANNEL_HASCAPTION_ARR[v];
            },
            operator_channelSignalTable_list: function (v, o, r) {
                var htmlArr = [];
                if (r.videoStatus == 100) {
                    htmlArr.push("<a href='' target='_blank'>审核打点</a>");
                }
                return htmlArr.join("&nbsp;");
            },
            videoStatus: function (v, r) {
                var ret = Record.Config.VIDEO_STATUS[v];
                if (ret == null) {
                    return "";
                }
                return ret;
            },
        },
        decodeRepeatCode: function (value, retType) {
            var retArr = [];
            $.each(Record.Config.REPEAT_CODE_ARR, function (i, codeValue) {
                if ((value & codeValue) == codeValue) {
                    retArr.push(i);
                }
            })
            if (retType != null && retType == "ch") {
                $.each(retArr, function (index, val) {
                    retArr[index] = Record.Config.REPEAT_CODE_CH_ARR[val];
                })
            } else {
                $.each(retArr, function (index, val) {
                    retArr[index] = Record.Config.REPEAT_CODE_ARR[val];
                })
            }
            if (retArr.length == 0) {
                retArr.push("未设定");
            }
            return retArr;
        },

        reloadHandler: function (data, tableId) {
            if (data != null) {
                Record.Util.logTips({content: data.msg ? data.msg : "创建成功", theme: data.code == "A00000" ? "success" : "error"});
                if (data.code == "A00000") {
                    if (tableId != null) {
                        $(tableId).trigger("reloadGrid")
                    } else {
                        $("#list").trigger("reloadGrid")
                    }
                }
            } else {
                console.log("callbackHandler no return data");
            }
        },
        checkValidPlanMode: function (entity) {
            if (entity.projectWorkers.length > 2 && entity.notifyType == 0) {
                Record.Util.logTips({ theme: "error", content: "请选择通知方式"});
                return false;
            }
            if (isNaN(entity.channelId)) {
                console.log(entity)
                Record.Util.logTips({ theme: "error", content: "请填写有效频道"});
                return false;
            }
            if (isNaN(entity.colId)) {
                Record.Util.logTips({ theme: "error", content: "请填写有效栏目"});
                return false;
            }
            if (entity.projectWorkers.length > 2 && entity.notifyType == 0) {
                Record.Util.logTips({ theme: "error", content: "请选择通知方式"});
                return false;
            }
            var checkArr = [];
            checkArr.push({value: entity.startDate, error: "开始日期格式有误", type: "self_design", checkCall: function (checkData, checkValue) {
                var rule = /^\d{4}-\d{2}-\d{2}$/;
                return rule.test(checkValue);
            }  })
            checkArr.push({value: entity.stopDate, error: "结束日期格式有误", type: "self_design", checkCall: function (checkData, checkValue) {
                var rule = /^\d{4}-\d{2}-\d{2}$/;
                return rule.test(checkValue);
            }  })


            if (entity.planType == 1) {
                checkArr.push({value: entity.startDayTime, error: "开始时间格式有误", type: "self_design", checkCall: function (checkData, checkValue) {
                    var rule = /^\d{2}:\d{2}:\d{2}$/;
                    return rule.test(checkValue);
                } })
                checkArr.push({value: entity.stopDayTime, error: "结束时间格式有误", type: "self_design", checkCall: function (checkData, checkValue) {
                    var rule = /^\d{2}:\d{2}:\d{2}$/;
                    return rule.test(checkValue);
                } })
                checkArr.push({value: entity.repeatCode, error: "重复周期没有选择", type: "gt", other: 0});
            } else if (entity.planType == 2) {
                checkArr.push({value: entity.fragmentOutput, error: "输出时间设置为0", type: "gt", other: 0});
            }

            checkArr.push({value: entity.channelId, error: "输出时间设置为0", type: "gt", other: 0});


            if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                console.log("interrupt checkValidPlanMode")
                return false;
            }
            return true;
        },

        preparePlanMode: function () {
            var sendData = {};
            var parentDom = $("form[role=addForm]");
            var tempId = parseInt(parentDom.find("input[name=edit_plan_id]").val());
            if (tempId > 0) {
                sendData.id = tempId;
            }

            sendData.channelId = parseInt(parentDom.find("input[name=channel_name]").suggest("getValue"));
            sendData.colId = parseInt(parentDom.find("select[name=col_name]").val());
            sendData.enable = parseInt(parentDom.find("select[name=enable]").val());
            sendData.status = 1;
            sendData.planType = parseInt(parentDom.find("input[name=plan_type]:checked").val());
            sendData.startDate = parentDom.find("input[name=start_date]").val();
            sendData.stopDate = parentDom.find("input[name=stop_date]").val();
            if (sendData.planType == 1) {
                sendData.startDayTime = parentDom.find("input[name=start_day_time]").val();
                sendData.stopDayTime = parentDom.find("input[name=stop_day_time]").val();
                sendData.repeatCode = Record.Util.calculateRepeatCodeValue(parentDom.find(".chosen-select").val())
                sendData.fragmentOutput = 0;
            } else if (sendData.planType == 2) {
                sendData.startDayTime = "";
                sendData.stopDayTime = "";
                sendData.repeatCode = 0;
                sendData.fragmentOutput = Record.Util.calculateFragmentOutput(parentDom.find("input[name=fragment_output_hour]").val(), parentDom.find("input[name=fragment_output_minute]").val());
            }
            var notifyType = Record.Util.calculateNotifyType(parentDom.find("input[name=notify_type]:checked"));
            var newDataArr = Record.Util.calculateProjectWorkers(parentDom.find("span.qui-tag"));

            sendData.notifyType = notifyType;
            sendData.projectWorkers = JSON.stringify(newDataArr);
            return sendData;
        },
        calculateNotifyType: function (notifyTypeArr) {
            var notifyType = 0;
            if (notifyTypeArr.length > 0) {
                $.each(notifyTypeArr, function (i, element) {
                    notifyType += parseInt($(element).val());
                })
            }
            return notifyType;
        },
        calculateProjectWorkers: function (workersArr) {
            var newDataArr = []
            if (workersArr.length > 0) {
                $.each(workersArr, function (i, element) {
                    newDataArr.push({ id: $(element).attr("data-tag-id"), label: $(element).attr("data-tag-label") });
                })
            }
            return newDataArr;
        },
        calculateFragmentOutput: function (hourString, minuteString) {
            var baseTime = 0;

            if ($.trim(hourString).length > 0) {
                baseTime = 60 * parseInt(hourString)
            }
            if ($.trim(minuteString).length > 0) {
                baseTime += parseInt(minuteString)
            }

            return baseTime;
        },
        calculateRepeatCodeValue: function (repeatCodeArr) {
            var repeatCodeValue = 0;
            if (repeatCodeArr != null) {
                $.each(repeatCodeArr, function (i, codeValue) {
                    repeatCodeValue = repeatCodeValue | parseInt(codeValue);
                })
            }
            return repeatCodeValue
        },

        sendAddRecordPlan: function () {
            var sendData = Record.Util.preparePlanMode();
            var flag = Record.Util.checkValidPlanMode(sendData);
            if (flag) {
                console.log(JSON.stringify(sendData));
                $("form[role=addForm]").dialog("close");
                Record.Dao.addRecordPlan({data: JSON.stringify(sendData)}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Record.Util.reloadHandler(data)
                    } else {
                        Record.Util.logTips({theme: "error", content: "创建失败"});
                    }
                })
            }

        },
        sendEditRecordPlan: function () {
            var sendData = Record.Util.preparePlanMode();
            var flag = Record.Util.checkValidPlanMode(sendData);
            if (flag) {
                console.log(JSON.stringify(sendData));
                Record.Dao.editRecordPlan({data: JSON.stringify(sendData)}, function (data) {
                    if (data != null && data.code == "A00000") {
                        if (data.data['retValue'] == -1) {
                            Record.Util.logTips({theme: "error", content: "修改失败"});
                        } else if (data.data['retValue'] == -2) {
                            Record.Util.logTips({theme: "error", content: "启用状态不可修改"});
                        } else if (data.data['retValue'] == 1) {
                            Record.Util.logTips({theme: "success", content: "修改成功"});
                            Record.Util.reloadHandler(data)
                            $("form[role=addForm]").dialog("close")
                        }
                    } else {
                        Record.Util.logTips({theme: "error", content: "修改失败"});
                    }
                })
            }

        },
        delPlan: function (entityId) {
            console.log("wait to do");
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    Record.Dao.deleteRecordPlan({id: entityId }, function (data) {
                        Record.Util.reloadHandler(data);
                    })
                }
            })
        },
        sendModifyRecordChannel: function () {
            var sendData = Record.Util.prepareChannelMode();
            Record.Util.checkValidChannelMode(sendData, function (flag) {
                if (flag == 5) {
                    $("form[role=modifyForm]").dialog("close");
                    console.log(JSON.stringify(sendData));
                    if (sendData.id) {
                        Record.Dao.editRecordChannel({data: JSON.stringify(sendData)}, function (data) {
                            if (data != null && data.code == "A00000") {
                                Record.Util.reloadHandler(data);
                                Record.Util.logTips({theme: "success", content: "修改成功"});
                            } else {
                                Record.Util.logTips({theme: "error", content: "修改失败"});
                            }
                        })
                    } else {
                        Record.Dao.addRecordChannel({data: JSON.stringify(sendData)}, function (data) {
                            if (data != null && data.code == "A00000") {
                                Record.Util.reloadHandler(data);
                                Record.Util.logTips({theme: "success", content: "添加成功"});
                            } else {
                                Record.Util.logTips({theme: "error", content: "添加失败"});
                            }
                        })
                    }
                }

                if (flag == 1) {
                    Record.Util.logTips({theme: "error", content: "频道名称不能为空"});
                }

                if (flag == 2) {
                    Record.Util.logTips({theme: "error", content: "频道代码不能为空"});
                }

                if (flag == 3) {
                    Record.Util.logTips({theme: "error", content: "频道名称已存在"});
                }
                if (flag == 4) {
                    Record.Util.logTips({theme: "error", content: "频道代码已存在"});
                }
            })

        },
        delChannel: function (entityId) {
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    Record.Dao.delRecordChannel({id: entityId }, function (data) {
                        Record.Util.reloadHandler(data);
                    })
                }
            })
        },
        prepareChannelMode: function () {
            var sendData = {};
            var parentDom = $("form[role=modifyForm]");
            var tempId = parseInt(parentDom.find("input[name=id]").val());
            if (tempId > 0) {
                sendData.id = tempId;
            }
            sendData.channelName = parentDom.find("input[name=channelName]").val().trim();
            sendData.channelCode = parentDom.find("input[name=channelCode]").val().trim();
            sendData.hasCaption = parseInt(parentDom.find("input[name=hasCaption]:checked").val());
            sendData.status = 1;
            return sendData;
        },
        checkValidChannelMode: function (entity, callback) {
            var parentDom = $("form[role=modifyForm]");
            var oldName = parentDom.find("input[name=channelName]").attr('oldV');
            var oldCode = parentDom.find("input[name=channelCode]").attr('oldV');

            if (entity.channelName == '') {
                callback.call(this, 1);
                return;
            }
            if (entity.channelCode == '') {
                callback.call(this, 2);
                return;
            }

            if (oldName && oldName == entity.channelName && oldCode && oldCode == entity.channelCode) {
                callback.call(this, 5);
                return;
            } else {
                Record.Dao.getRecordChannelList({ 'paramsObj': JSON.stringify({'EQS_channelName': entity.channelName})}, function (data) {
                    if (oldName != entity.channelName && data != null && data.code == "A00000" && data.data.totalCount > 0) {
                        //频道名称已存在
                        callback.call(this, 3);
                        return;
                    } else {
                        Record.Dao.getRecordChannelList({ 'paramsObj': JSON.stringify({'EQS_channelCode': entity.channelCode})}, function (data1) {
                            if (oldCode != entity.channelCode && data1 != null && data.code == "A00000" && data1.data.totalCount > 0) {
                                //频道代码已存在
                                callback.call(this, 4);
                                return;
                            } else {
                                callback.call(this, 5);
                            }
                        });
                    }
                });
            }

        },
        openChannelModifyDlg: function (entityId) {
            var parentDom = $("form[role=modifyForm]");
            parentDom.dialog("open");
            parentDom.find("input[name=id]").val("");
            parentDom.find("input[name=channelName]").val("").removeAttr('oldV');
            parentDom.find("input[name=channelCode]").val("").removeAttr('oldV');
            parentDom.find("input[name=hasCaption][value=1]").click();

            if (entityId > 0) {
                Record.Dao.getRecordChannelList({paramsObj: JSON.stringify({EQL_id: entityId})}, function (data) {
                    if (data != null && data.code == "A00000") {
                        console.log(JSON.stringify(data));
                        var result = data.data.result[0];
                        parentDom.find("input[name=id]").val(result.id);
                        parentDom.find("input[name=channelName]").val(result.channelName).attr('oldV', result.channelName);
                        parentDom.find("input[name=channelCode]").val(result.channelCode).attr('oldV', result.channelCode);
                        ;
                        parentDom.find("input[name=hasCaption][value=" + result.hasCaption + "]").click();
                    } else {
                        Record.Util.logTips({theme: "error", content: "访问数据失败"});
                    }
                })
                parentDom.dialog("open");
            } else {

                parentDom.dialog("open");
            }
        },
        logTips: function (options) {
            EpgWeb.Plugin.showTips(options);
        },
        openPlanModifyDlg: function (entityId, flag) {
            Record.Util.doAddFormReset();
            var parentDom = $("form[role=addForm]");
            if (flag && flag == 1 && entityId > 0) {
                Record.Dao.getColList({paramsObj: JSON.stringify({ "EQL_channelId": entityId, "EQI_status": "1" }), dataMode: "simple", pageSize: 100}, function (retData) {
                    Record.Util.fillRelationColSelect(retData);
                    parentDom.dialog("option", "title", "新建计划").dialog('open');
                    parentDom.find("input[name=plan_type][value='1']").click();
                    parentDom.find("button[name=edit_plan_btn]").hide();
                    parentDom.find("button[name=add_plan_btn]").show();
                })
            } else if (entityId > 0) {
                Record.Dao.getRecordPlan(entityId, function (data) {
                    if (data != null && data.code == "A00000") {
                        console.log(JSON.stringify(data));
                        Record.Dao.getRecordChannelList({paramsObj: JSON.stringify({EQL_id: data.data.channelId}), dataMode: "simple"}, function (gdata) {
                            if (gdata != null && gdata.code == "A00000") {
                                parentDom.dialog("option", "title", "修改计划").dialog('open');
                                parentDom.dialog("open");
                                parentDom.find("button[name=add_plan_btn]").hide();
                                parentDom.find("button[name=edit_plan_btn]").show();
                                data.data.channelName = gdata.data.result[0].channelName;
                                Record.Util.doAddFormFillData(data.data);
                            }
                        })
                    } else {
                        Record.Util.logTips({theme: "error", content: "访问数据失败"});
                    }
                })
            } else {
                parentDom.dialog("option", "title", "新建计划").dialog('open');
                parentDom.find("input[name=plan_type][value='1']").click();
                parentDom.find("button[name=edit_plan_btn]").hide();
                parentDom.find("button[name=add_plan_btn]").show();
            }
        },
        doAddFormReset: function () {
            var parentDom = $("form[role=addForm]");
            parentDom[0].reset();
            var channelName = Com.url.getParameter("channel_name");
            var channelId = Com.url.getParameter("channel_id");
            parentDom.find("select[name=col_name]").html("");
            parentDom.find("select[name=enable]").removeAttr('status');
            parentDom.find('input[name="start_date"]').datepicker("option", "maxDate", null);
            parentDom.find('input[name="stop_date"]').datepicker("option", "minDate", null);
            parentDom.find(".chosen-select").val(null);
            parentDom.find(".chosen-select").attr('disabled',false).trigger('chosen:updated')
            parentDom.find("a.qui-tag-remove").click();
            //parentDom.find("input[name=plan_type]").attr("disabled",false);
            parentDom.find("select[name=enable]").trigger('change');
            if(channelName && channelId){
                $("input[name=channel_name]").val( decodeURI(channelName)).attr('disabled','disabled');
                parentDom.find("input[name=channel_name]").suggest("setValue", {id: channelId, label: decodeURI(channelName)});
            }
        },
        doAddFormFillData: function (element) {
            var parentDom = $("form[role=addForm]");
            parentDom.find("input[name=edit_plan_id]").val(element.id);
            parentDom.find("input[name=channel_name]").suggest("setValue", {id: element.channelId, label: element.channelName});
            Record.Dao.getColList({paramsObj: JSON.stringify({ "EQL_channelId": element.channelId, "EQI_status": "1" }), dataMode: "simple", pageSize: 100}, function (retData) {
                Record.Util.fillRelationColSelect(retData, element.colId);
            })
            if (element.projectWorkers != null && element.projectWorkers.length > 2) {
                var workerArr = JSON.parse(element.projectWorkers);
                $.each(workerArr, function (i, element) {
                    parentDom.find("input[name=project_workers]").suggest("addValue", element);
                })
            }
            if ((element.notifyType & 1) == 1) {
                parentDom.find("input[name=notify_type][value='1']").prop("checked", true);
            }
            if ((element.notifyType & 2) == 2) {
                parentDom.find("input[name=notify_type][value='2']").prop("checked", true);
            }
            if ((element.notifyType & 4) == 4) {
                parentDom.find("input[name=notify_type][value='4']").prop("checked", true);
            }
            parentDom.find("select[name=enable]").val(element.enable).attr('status',element.enable);
            parentDom.find("input[name=plan_type][value=" + element.planType + "]").click();

            parentDom.find('input[name="start_date"]').datepicker("setDate", element.startDate);
            parentDom.find('input[name="stop_date"]').datepicker("setDate", element.stopDate);
            parentDom.find('input[name="stop_date"]').datepicker("option", "minDate", element.startDate);
            parentDom.find('input[name="start_date"]').datepicker("option", "maxDate", element.stopDate);
            if (element.planType == 1) {
                parentDom.find('input[name="start_day_time"]').timepicker("setTime", element.startDayTime);
                parentDom.find('input[name="stop_day_time"]').timepicker("setTime", element.stopDayTime);
                parentDom.find('input[name="start_day_time"]').timepicker("option", "minTime", element.startDayTime);
                parentDom.find('input[name="stop_day_time"]').timepicker("option", "maxTime", element.stopDayTime);
                parentDom.find('.chosen-select').val(Record.Util.decodeRepeatCode(element.repeatCode));
                parentDom.find('.chosen-select').trigger('chosen:updated');
            } else if (element.planType == 2) {
                parentDom.find("input[name=fragment_output_hour]").val(element.fragmentOutput / 60 >> 0);
                parentDom.find("input[name=fragment_output_minute]").val(element.fragmentOutput % 60);
            }
            parentDom.find("select[name=enable]").trigger('change');
        },
        fillRelationColSelect: function (retData, colId) {
            var parentDom = $("form[role=addForm]");
            var container = parentDom.find("select[name=col_name]");
            container.html("");
            if (retData != null && retData.code == "A00000") {
                $.each(retData.data.result, function (i, element) {
                    $("<option attr-channel-id='" + element.channelId + "' value='" + element.id + "'>" + element.colName + "</option>").appendTo(container);
                })
            }
            if (colId) {
                parentDom.find("select[name=col_name]").val(colId)
            }
            ;
        },
        changeTaskStatus: function (entityId) {
            SystemDialog.queryConfirm("确认取消任务？", function (flag) {
                if (flag === true) {
                    var sendData = {id: entityId, taskStatus: Record.Config.TASK_STATUS_ENUM_VALUE.TASK_CANCEL}
                    Record.Dao.editRecordTask({data: JSON.stringify(sendData)}, function (data) {
                        Record.Util.reloadHandler(data);
                    })
                }
            })
        }
    });
});
define(
    '../record/Record.Dao',['require','exports','module'],function (require, exports, module) {

        Record.Dao = $.extend({}, EpgWeb.Dao, {
            deleteRecordPlan:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doPlanDelUrl,"post",sendData,handler,"/record/plan/del");
            },
            addRecordPlan:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doPlanSaveUrl,"post",sendData,handler,"/record/plan/save");
            },
            editRecordPlan:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doPlanEditUrl,"post",sendData,handler,"/record/plan/edit");
            },
            getRecordPlan:function(entityId,handler){
                this.sendAjax(Record.urlConfig.getPlanByIdUrl,"post",{id:entityId},handler,"/record/plan/getById");
            },
            getColList:function(sendData,handler){
                this.sendAjax(Record.urlConfig.getRecordColUrl,"post",sendData,handler,"/record/col/list");
            },
            getRecordChannelList :function(sendData,handler){
                this.sendAjax(Record.urlConfig.getRecordChannelUrl ,"post",sendData,handler,"/record/channel/list");
            },
            editRecordTask:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doTaskEditUrl,"post",sendData,handler,"/record/task/edit");
            },
            addRecordChannel:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doChannelAddUrl,"post",sendData,handler,"/record/channel/save");
            },
            editRecordChannel:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doChannelEditUrl,"post",sendData,handler,"/record/channel/edit");
            },
            delRecordChannel:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doChannelDelUrl,"post",sendData,handler,"/record/channel/del");
            }
        });
        Record.Dao.cfgName = {
            logType:"ticket_log",
            workType:"ticket_worker"
        }
    }
);
define(
    '../record/Record.Action',['require','exports','module'],function (require, exports, module) {

        Record.Action = (function () {
            var recordPlanList = null;
            var recordTaskList = null;
            var recordChannelList = null;
            var recordChannelSginalTableList = null;

            function runPlanList() {
                if (!recordPlanList) {
                    recordPlanList = new Record.PlanGrid($.extend(true, {
                        $grid: $("#list"),
                        $container: $("#j-view-container"),
                        type: 0
                    }, {}));
                }
                EpgWeb.Plugin.Validate.bindDefaultHandler(function (msg) {
                    EpgWeb.Plugin.showTips({theme: "error", content: msg});
                })
                recordPlanList.doInit();
                console.log('plan grid run');
            }

            function runTaskList() {
                if (!recordTaskList) {
                    recordTaskList = new Record.TaskGrid($.extend(true, {
                        $grid: $("#list"),
                        $container: $("#j-view-container"),
                        type: 0
                    }, {}));
                }
                recordTaskList.doInit();
                console.log('task grid run');
            }

            function runChannelList() {
                if (!recordChannelList) {
                    recordChannelList = new Record.ChannelGrid($.extend(true, {
                        $grid: $("#list"),
                        $container: $("#j-view-container"),
                        type: 0
                    }, {}));
                }
                recordChannelList.doInit();
                console.log('channel grid run');
            }

            function runChannelSignalTableList() {
                if (!recordChannelSginalTableList) {
                    recordChannelSginalTableList = new Record.ChannelSignalTableGrid($.extend(true, {
                        $grid: $("#list"),
                        $container: $("#j-view-container"),
                        type: 0
                    }, {}));
                }
                recordChannelSginalTableList.doInit();
                console.log('channelSginalTableList grid run');
            }

            return {
                runPlanList: runPlanList,
                runTaskList: runTaskList,
                runChannelList: runChannelList,
                runChannelSignalTableList: runChannelSignalTableList
            }
        })();
    }
);
define(
    '../record/Record.ChannelGrid',['require','exports','module'],function (require, exports, module) {

        Record.ChannelGrid = function (options) {
            this.dao = Record.Dao;
            this.config = Record.Config;
            this.util = Record.Util;
            this.options = options || {};
        };

        Com.inherits(Record.ChannelGrid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;

                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.bindEvent();
                    self.initSuggest();
                    self.initGrid();
                    self.initDlg();
                    self.query();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            bindEvent: function () {
                var self = this;

                $("button[name=query_btn]").bind("click", function (event) {
                    self.query();
                })

                $("button[name=open_new_dlg_btn]").bind("click", function (event) {
                    Record.Util.openChannelModifyDlg();
                })
            },
            initSuggest: function () {
                var self = this;
                var channelSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/record/channel/list");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        source: Record.urlConfig.getRecordChannelUrl,
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var jsonObj = { LIKES_channelName: $.trim(term), EQI_status: 1 };
                            return { "dataMode": "simple", paramsObj: JSON.stringify(jsonObj) }
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["channelName"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }

                $("input[name=LIKES_channelName]").suggest(channelSuggest.options);

            },
            initGrid: function (options) {
                var self = this;
                self.$grid = self.options.$grid;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.CHANNEL_DATA_LIST);
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);
            },
            query: function (callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            getParam: function () {
                var params = {};
                var inputArr = $('form[role="queryForm"]').find("input[role=query-text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("name")] = element.value.trim()
                    }
                })
                params["EQI_status"] = 1;
                console.log("params:" + JSON.stringify(params));

                return { paramsObj: JSON.stringify(params) };
            },
            initDlg: function () {
                var self = this;
                self.initmodifyFormDlg();
            },

            initmodifyFormDlg: function () {
                $("form[role=modifyForm]").dialog({
                    title: "编辑频道",
                    autoOpen: false,
                    height: 300,
                    width: 540,
                    modal: true
                })
                $("button[name=save_btn]").bind("click", function (event) {
                    Record.Util.sendModifyRecordChannel();
                })
                $("button[name=cancel_btn]").bind("click", function (event) {
                    $("form[role=modifyForm]").dialog("close")
                })
            }
        });

    }
);
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Program.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-03-01
 */
define(
    '../record/Record.Task',['require','exports','module'],function (require, exports, module) {
        Record.Task = (function () {
            var getLegoCategory = function (typeName,  regName) {
                if (regName == null) {
                    regName = typeName;
                }
                var requestData = {url: Record.Constant.thirdUrl_channel_url, type: "get", needCookie: true};
                return {
                    regName: regName,
                    options: {
                        type: "post",
                        url: "/api/redirect",
                        dataType: "json",
                        data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                    }
                }
            }

            return {
                getLegoCategory:getLegoCategory
            }
        })()
    }
);
define(
    '../record/Record.Signal_Action',['require','exports','module'],function(require, exports, module){

        Record.Signal_Action = (function() {
            var recordSignalList = null;
            function run(){
                if (!recordSignalList) {
                    recordSignalList = new Record.Signal_Grid($.extend(true, {
                        $grid:$("#list"),
                        $container:$("#j-view-container"),
                        type: 0
                    }, {}));
                }
                recordSignalList.doInit();
                console.log('record signal grid run');
            }

            return {
                run:run
            }
        })();


    }
);

define('../record/Record.Signal_Config',['require','exports','module'],function (require, exports, module) {

    Record.Signal_Config = $.extend({}, {}, {
        TABLE_COLMODEL_CONFIG: {
            id: {
                name: "id",
                index: 'id',
                title: false,
                width: 50,
                align: "center",
                sortable: false
            },
            signalName: {
                name: "signalName",
                index: 'signalName',
                title: false,
                width: 120,
                align: "center",
                sortable: false
            },
            signalAddress: {
                name: "signalAddress",
                index: 'signalAddress',
                title: false,
                width: 160,
                align: "center",
                sortable: false
            },
            priority: {
                name: "priority",
                index: 'priority',
                title: false,
                width: 80,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Signal_Util.formatter.priority(v, o, r);
                }

            },
            serverCluster: {
                name: "serverCluster",
                index: 'serverCluster',
                title: false,
                width: 100,
                align: "center",
                sortable: false
            },
            serverIp: {
                name: "serverIp",
                index: 'serverIp',
                title: false,
                width: 180,
                align: "center",
                sortable: false
            },
            channelName: {
                name: "channelName",
                index: 'channelName',
                title: false,
                width: 100,
                align: "center",
                sortable: false
            },
            opUser: {
                name: "opUser",
                index: 'opUser',
                title: false,
                width: 150,
                align: "center",
                sortable: false
            },
            addTime: {
                name: "createTime",
                index: 'createTime',
                title: false,
                width: 150,
                align: "center",
                sortable: false
            },

            status: {
                name: "status",
                index: 'status',
                title: false,
                width: 80,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Signal_Util.formatter.status(v, o, r);
                }
            },
            status_channel_signal: {
                name: "status",
                index: 'status',
                title: false,
                width: 60,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Signal_Util.formatter.status_channel_signal(v, o, r);
                }
            },
            operator_signal_list: {
                title: false,
                width: 120,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Signal_Util.formatter.operator_signal_list(v, o, r);
                }
            },

            operator_channel_signal_list: {
                title: false,
                width: 100,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                    return Record.Signal_Util.formatter.operator_channel_signal_list(v, o, r);
                }
            }
        },
        SIGNAL_DATA_LIST: {
            url: Record.urlConfig.getSignalLibraryListUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/record/signal/libraryList");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 20,
            mtype: "post",
            datatype: "json",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            shrinkToFit: false,
            colNames: ["信号ID","信号名称","流地址", "优先级", "服务器集群",  "创建人", "创建时间", "状态", "操作"],
            colModel: ['id',"signalName", "signalAddress", "priority",  "serverCluster","opUser","addTime","status","operator_signal_list"],
            pager: "#pager"
        },

        CHANNEL_SIGNAL_DATA_LIST: {
            url: Record.urlConfig.getChannelSignalLibraryListUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/record/channel/signal/libraryList");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 20,
            mtype: "post",
            datatype: "json",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            shrinkToFit: false,
            colNames: ["ID","信号名称","流地址", "优先级", "服务器集群", "服务器", "频道","创建人", "创建时间", "状态", "操作"],
            colModel: ['id',"signalName", "signalAddress", "priority",  "serverCluster","serverIp","channelName","opUser","addTime","status_channel_signal","operator_channel_signal_list"],
            pager: "#pager"
        },

        CODE_SUC :"A00000",
    });
});
define(
    '../record/Record.Signal_Grid',['require','exports','module'],function (require, exports, module) {

        Record.Signal_Dao = $.extend({}, EpgWeb.Dao, {
            addRecordSignal:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doSignalSaveUrl,"post",sendData,handler,"/record/signal/save");
            },
            deleteRecordSignal:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doSignalDelUrl,"post",sendData,handler,"/record/signal/del");
            },
            editRecordSignal:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doSignalEditUrl,"post",sendData,handler,"/record/signal/edit");
            },
            getRecordSignal:function(entityId,handler){
                this.sendAjax(Record.urlConfig.doSignalGetByIdUrl,"post",{id:entityId},handler,"/record/signal/getById");
            }
        });

        Record.Signal_Grid = function (options) {
            this.dao = Record.Signal_Dao;
            this.config = Record.Signal_Config;
            this.util = Record.Signal_Util;
            this.options = options || {};
        };

        Com.inherits(Record.Signal_Grid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.bindEvent();
                    self.initGrid();
                    self.initDlg();
                    self.initSuggest();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            bindEvent: function () {
                var self = this;

                //创建请求
                var $sendAddButton = $("button[name=add_signal_btn]");
                $sendAddButton.bind("click", function (event) {
                    Record.Signal_Util.sendAddRecordSignal();
                });

                //修改请求
                var $sendEditButton = $("button[name=edit_signal_btn]");
                $sendEditButton.bind("click", function (event) {
                    Record.Signal_Util.sendEditRecordSignal();
                });

                //新建
                $("button[name=open_new_dlg_btn]").bind("click", function (event) {
                    $sendAddButton.show();
                    $sendEditButton.hide();
                    $("form[role=addForm]").dialog("open");
                    $("form[role=addForm]")[0].reset();
                });

                //取消
                $("button[name=cancel_btn]").bind("click", function (event) {
                    $("form[role=addForm]").dialog("close")
                });

                //搜索
                $("button[name=query_btn]").bind("click", function (event) {
                    self.query();
                })


            },

            initGrid: function (options) {
                var self = this;
                self.$grid = self.options.$grid;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.SIGNAL_DATA_LIST);
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);

                //简单响应式
                $(window).resize(function(){
                    self.$grid.setGridWidth($(window).width()*0.9);
                });


            },
            query: function (callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            getParam: function () {
                var params = {};
                var inputArr = $('form[role="queryForm"]').find("input[role=query-text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("name")] = element.value.trim()
                    }
                })

                console.log("query params:" + JSON.stringify(params));
                return { paramsObj: JSON.stringify(params) };
            },
            initDlg: function () {
                $("form[role=addForm]").dialog({
                    title: "新建信号",
                    autoOpen: false,
                    height: 640,
                    width: 840,
                    modal: true
                })
            },
            initSuggest: function () {
                var ClusterSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/sginal/server/clusterList");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        select: function (event, object) {
                            var obj = { "clusterName": Number(object.item.id) };
                            return true;
                        },
                        source: "/api/sginal/server/clusterList",
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            return { "clusterName": $.trim(term) }
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }
                $("input[name=server_cluster_name]").suggest(ClusterSuggest.options);
            }
        });

    }
);
define('../record/Record.Signal_Util',['require','exports','module'],function (require, exports, module) {
    Record.Signal_Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            operator_signal_list: function (v, o, r) {
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='Record.Signal_Util.openSignalModifyDlg(" + r.id + ")' style='margin-right: 10px'>修改</a>");
                htmlArr.push("<a href='javascript:;' onclick='Record.Signal_Util.delSignal(" + r.id + ")' >删除</a>");
                return htmlArr.join("");
            },
            operator_channel_signal_list: function (v, o, r) {
                var htmlArr = [];
                // console.error(JSON.stringify(r))
                if (r.status === 1) {
                    htmlArr.push("<a href='javascript:;' onclick='Record.Signal_Util.stopChannelSignal(" + r.id + ")' style='margin-right: 10px'>关闭</a>");
                }else{
                    htmlArr.push("<a href='javascript:;' onclick='Record.Signal_Util.startChannelSignal(" + r.id + ")' style='margin-right: 10px'>启动</a>");
                }
                // htmlArr.push("<a href='javascript:;' onclick='Record.Signal_Util.openChannelSignalModifyDlg(" + r.id + ")' style='margin-right: 10px'>修改</a>");
                htmlArr.push("<a href='javascript:;' onclick='Record.Signal_Util.delChannelSignal(" + r.id + ")' >删除</a>");
                return htmlArr.join("");
            },
            status: function (v, o, r) {
                return v === 1 ? "上线" : "下线";
            },

            status_channel_signal: function (v, o, r) {
                return v === 1 ? "启动" : "关闭";
            },
            priority: function (v, o, r) {
                var result_priority = "";
                switch (v) {
                    case 1 :
                        result_priority = "低";
                        break;
                    case 2 :
                        result_priority = "较低";
                        break;
                    case 3 :
                        result_priority = "中";
                        break;
                    case 4 :
                        result_priority = "高";
                        break;

                    default:
                        break;
                }

                return result_priority;

            }

        },
        reloadHandler: function (data) {
            if (data != null) {
                EpgWeb.Plugin.showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
                if (data.code == "A00000") {
                    $("#list").trigger("reloadGrid")
                }
            } else {
                console.log("callbackHandler no return data");
            }
        },

        prepareSignalMode: function () {
            var sendData = {};
            var parentDom = $("form[role=addForm]");
            var signalId = parentDom.find("input[name=signal_id]").val();
            if(signalId.length !== 0 ){
                sendData.id = signalId;
            }
            sendData.signalName = parentDom.find("input[name=signal_name]").val().trim();
            sendData.signalAddress = parentDom.find("input[name=signal_address_name]").val().trim();
            sendData.serverCluster = parentDom.find("input[name=server_cluster_name]").val().trim();
            sendData.priority = parseInt(parentDom.find("select[name=priority_name]").val());
            sendData.status = parseInt(parentDom.find("select[name=status]").val());
            if ($.trim(sendData.signalName).length === 0) {
                EpgWeb.Plugin.showTips({ theme: "error", content: "请填写信号名称"});
                return null;
            }
            if ($.trim(sendData.signalAddress).length === 0) {
                EpgWeb.Plugin.showTips({ theme: "error", content: "请填写信号流地址"});
                return null;
            }

            if ($.trim(sendData.serverCluster).length === 0) {
                EpgWeb.Plugin.showTips({ theme: "error", content: "请选择服务器集群"});
                return null;
            }

            if (sendData.priority  === 0) {
                EpgWeb.Plugin.showTips({ theme: "error", content: "请选择优先级"});
                return null;
            }
            console.log("prepareModel: "+JSON.stringify(sendData));
            return sendData;
        },

        sendAddRecordSignal: function () {
            var model = Record.Signal_Util.prepareSignalMode();
            var sendData = JSON.stringify(model);
            if(model != null) {
                Record.Signal_Dao.addRecordSignal({data:sendData}, function (data) {
                    if (data != null ) {
                        switch (data.code) {
                            case "A00000":
                                Record.Signal_Util.reloadHandler(data);
                                $("form[role=addForm]").dialog("close");
                                break;
                            case "EPG00501":
                                EpgWeb.Plugin.showTips({theme: "error", content: "创建失败：信号名称重复！"});
                                break;
                            default:
                                EpgWeb.Plugin.showTips({theme: "error", content: "接口返回异常："+data.code});
                                console.log("request : addRecordSignal data.code " + data.code);
                                break;
                        }

                    } else {
                        EpgWeb.Plugin.showTips({theme: "error", content: "创建失败"});
                    }

                })
            }else {
                console.log("sendAddRecordSignal sendData == null ?!");
            }

        },

        sendEditRecordSignal: function () {
            var model = Record.Signal_Util.prepareSignalMode();
            var sendData = JSON.stringify(model);
            console.log("---" + sendData);

            function editSignal() {
                Record.Signal_Dao.editRecordSignal({data: sendData}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Record.Util.reloadHandler(data)
                    } else {
                        EpgWeb.Plugin.showTips({theme: "error", content: "修改失败"});
                    }
                    $("form[role=addForm]").dialog("close")

                });
            }
            if(model != null) {
                //修改时判断model是否设置下线，是的话查询关联信号，关联了提示确认窗口
                if (model.status === 0) {
                    var params = {paramsObj: JSON.stringify({'EQL_recordChannelSignal.signal_id': model.id})};
                    Record.Channel_Signal_Dao.getRecordChannelSignalList(params, function (data) {
                        if (data != null && data.code == "A00000") {
                            SystemDialog.queryConfirm("该信号已经被关联，确认下线吗？", function (flag) {
                                if (flag === true) {
                                    editSignal();
                                }
                            })

                        }else{
                            editSignal();
                        }

                    });
                }else{
                    editSignal();
                }

            }else{
                console.log("sendEditRecordSignal sendData == null ?!");
            }

        },


        delSignal: function (entityId) {
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    Record.Signal_Dao.deleteRecordSignal({id: entityId }, function (data) {
                        Record.Util.reloadHandler(data);
                    })
                }
            })
        },
        openSignalModifyDlg: function (entityId) {
            var parentDom = $("form[role=addForm]");
            if (entityId > 0) {
                Record.Signal_Dao.getRecordSignal(entityId, function (data) {
                    if (data != null) {
                        //显示修改按钮
                        var $sendAddButton = $("button[name=add_signal_btn]");
                        var $sendEditButton = $("button[name=edit_signal_btn]");
                        $sendAddButton.hide();
                        $sendEditButton.show();
                        //赋值
                        var resultData = data.data;
                        parentDom.find("input[name=signal_id]").val(resultData.id);
                        parentDom.find("input[name=signal_name]").val(resultData.signalName);
                        parentDom.find("input[name=signal_address_name]").val(resultData.signalAddress);
                        parentDom.find("input[name=server_cluster_name]").val(resultData.serverCluster);
                        parentDom.find("select[name=priority_name]").val(resultData.priority);
                        parentDom.find("select[name=status]").val(resultData.status);

                        console.log("modify data: " + JSON.stringify(data));
                        parentDom.dialog("option", "title", "修改信号").dialog("open");
                    }else {

                    }
                })
            } else {

                EpgWeb.Plugin.showTips({theme: "error", content: "id 异常"});
            }
        },

        sendAddRecordChannelSignal: function () {
            var model = Record.Signal_Util.prepareChannelSignalMode();
            var sendData = JSON.stringify(model);
            if(model != null) {
                Record.Channel_Signal_Dao.addRecordChannelSignal({data:sendData}, function (data) {
                    if (data != null ) {
                        switch (data.code) {
                            case "A00000":
                                Record.Signal_Util.reloadHandler(data);
                                $("form[role=addForm]").dialog("close");
                                break;
                            case "EPG00501":
                                EpgWeb.Plugin.showTips({theme: "error", content: "创建失败：信号名称重复！"});
                                break;
                            default:
                                EpgWeb.Plugin.showTips({theme: "error", content: "接口返回异常："+data.code});
                                console.log("request : addRecordSignal data.code " + data.code);
                                break;
                        }

                    } else {
                        EpgWeb.Plugin.showTips({theme: "error", content: "创建失败"});
                    }

                })
            }else {
                console.log("sendAddRecordChannelSignal sendData == null ?!");
            }

        },
        sendEditRecordChannelSignal: function () {
            var model = Record.Signal_Util.prepareChannelSignalMode();
            var sendData = JSON.stringify(model);
            console.log("---" + sendData);
            if(model != null) {
                Record.Channel_Signal_Dao.editRecordChannelSignal({data:sendData}, function (data) {
                    if (data != null && data.code == "A00000") {
                        Record.Util.reloadHandler(data)
                    } else {
                        EpgWeb.Plugin.showTips({theme: "error", content: "修改失败"});
                    }
                    $("form[role=addForm]").dialog("close")

                })
            }else{
                console.log("sendEditRecordSignal sendData == null ?!");
            }

        },

        prepareChannelSignalMode: function () {
            var sendData = {};
            var parentDom = $("form[role=addForm]");
            var channelId = $("#title_channel_id").text();
            sendData.signalId = parentDom.find("input[name=signal_name]").attr("data-id");
            sendData.signalName = parentDom.find("input[name=signal_name]").val().trim();
            sendData.channelId = channelId;
            if ($.trim(sendData.signalName).length === 0) {
                EpgWeb.Plugin.showTips({ theme: "error", content: "请填写信号名称"});
                return null;
            }
            if ($.trim(sendData.signalId).length === 0) {
                EpgWeb.Plugin.showTips({ theme: "error", content: "信号名称有误"});
                return null;
            }

            console.log("prepareModel: "+JSON.stringify(sendData));
            return sendData;
        },
        delChannelSignal: function (entityId) {
            console.log("wait to do");
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    Record.Channel_Signal_Dao.deleteRecordChannelSignal({id: entityId }, function (data) {
                        if (data != null ) {
                            switch (data.code) {
                                case "A00000":
                                    Record.Signal_Util.reloadHandler(data);
                                    break;
                                case "EPG00502":
                                    EpgWeb.Plugin.showTips({theme: "error", content: data.msg});
                                    break;
                                default:
                                    EpgWeb.Plugin.showTips({theme: "error", content: data.msg});
                                    console.log("request : delChannelSignal data.code " + data.code);
                                    break;
                            }

                        } else {
                            EpgWeb.Plugin.showTips({theme: "error", content: "删除失败"});
                        }

                    })
                }
            })
        },

        startChannelSignal: function (entityId) {
            console.log("wait to do");
            SystemDialog.queryConfirm("确认启动？", function (flag) {
                if (flag === true) {
                    Record.Channel_Signal_Dao.startRecordChannelSignal({id: entityId }, function (data) {
                        Record.Util.reloadHandler(data);
                    })
                }
            })
        },

        stopChannelSignal: function (entityId) {
            console.log("wait to do");
            SystemDialog.queryConfirm("确认停止？", function (flag) {
                if (flag === true) {
                    Record.Channel_Signal_Dao.stopRecordChannelSignal({id: entityId }, function (data) {
                        Record.Util.reloadHandler(data);
                    })
                }
            })
        },
        openChannelSignalModifyDlg: function (entityId) {
            var parentDom = $("form[role=addForm]");
            if (entityId > 0) {
                Record.Signal_Dao.getRecordChannelSignal(entityId, function (data) {
                    if (data != null) {
                        //显示修改按钮
                        var $sendAddButton = $("button[name=add_channel_signal_btn]");
                        var $sendEditButton = $("button[name=edit_channel_signal_btn]");
                        $sendAddButton.hide();
                        $sendEditButton.show();
                        //赋值
                        var resultData = data.data;
                        parentDom.find("input[name=signal_id]").val(resultData.id);
                        parentDom.find("input[name=signal_name]").val(resultData.signalName);
                        parentDom.find("input[name=signal_address_name]").val(resultData.signalAddress);
                        parentDom.find("input[name=server_cluster_name]").val(resultData.serverCluster);
                        parentDom.find("select[name=priority_name]").val(resultData.priority);
                        parentDom.find("select[name=status]").val(resultData.status);

                        console.log("modify data: " + JSON.stringify(data));
                        parentDom.dialog("option", "title", "修改信号").dialog("open");
                    }else {

                    }
                })
            } else {

                EpgWeb.Plugin.showTips({theme: "error", content: "id 异常"});
            }
        }

    });
});
define(
    '../record/Record.Channel_Signal_Action',['require','exports','module'],function(require, exports, module){

        Record.Channel_Signal_Action = (function() {
            var recordSignalList = null;
            function run(){
                if (!recordSignalList) {
                    recordSignalList = new Record.Channel_Signal_Grid($.extend(true, {
                        $grid:$("#list"),
                        $container:$("#j-view-container"),
                        type: 0
                    }, {}));
                }
                recordSignalList.doInit();
                console.log('record Channel_Signal_Action grid run');
            }

            return {
                run:run
            }
        })();


    }
);

define(
    '../record/Record.Channel_Signal_Grid',['require','exports','module'],function (require, exports, module) {

        Record.Channel_Signal_Dao = $.extend({}, EpgWeb.Dao, {
            addRecordChannelSignal:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doChannelSignalSaveUrl,"post",sendData,handler,"/record/channel/signal/save");
            },
            deleteRecordChannelSignal:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doChannelSignalDelUrl,"post",sendData,handler,"/record/channel/signal/del");
            },
            editRecordChannelSignal:function(sendData,handler){
                this.sendAjax(Record.urlConfig.doChannelSignalEditUrl,"post",sendData,handler,"/record/channel/signal/edit");
            },
            getRecordChannelSignal:function(entityId,handler){
                this.sendAjax(Record.urlConfig.doChannelSignalGetByIdUrl,"post",{id:entityId},handler,"/record/channel/signal/getById");
            },
            getRecordChannelSignalList :function(sendData,handler){
                this.sendAjax(Record.urlConfig.getChannelSignalLibraryListUrl ,"post",sendData,handler,"/record/channel/signal/libraryList");
            },
            startRecordChannelSignal :function(sendData,handler){
                this.sendAjax(Record.urlConfig.doChannelSignalStartUrl ,"post",sendData,handler,"/record/channel/signal/start");
            },
            stopRecordChannelSignal :function(sendData,handler){
                this.sendAjax(Record.urlConfig.doChannelSignalStopUrl ,"post",sendData,handler,"/record/channel/signal/stop");
            },

        });

        Record.Channel_Signal_Grid = function (options) {
            this.dao = Record.Channel_Signal_Dao;
            this.config = Record.Signal_Config;
            this.util = Record.Signal_Util;
            this.options = options || {};
        };

        Com.inherits(Record.Channel_Signal_Grid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.initChannel();
                    self.bindEvent();
                    self.initGrid();
                    self.initDlg();
                    self.initSuggest();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            initChannel:function () {
                //get channelId -> name code
                var channelId = Ancestor.Util.getUrlId("channel_id");
                if(channelId > 0) {
                    Record.Dao.getRecordChannelList({paramsObj: JSON.stringify({EQL_id: channelId})}, function (data) {
                        if (data != null && data.code == "A00000") {
                            var result = data.data.result[0];
                            $("#title_channel_id").text(result.id);
                            $("#title_channel_name").text(result.channelName);
                            $("#title_channel_code").text(result.channelCode);

                            $("#label_channel_id").text(result.id);
                            $("#label_channel_name").text(result.channelName);
                            $("#label_channel_code").text(result.channelCode);


                        } else {
                            Record.Util.logTips({theme: "error", content: "访问频道数据失败"});
                        }
                    });
                }else {
                    Record.Util.logTips({theme: "error", content: "channel_id 不正确！"});

                }


            },

            bindEvent: function () {

                //创建请求
                var $sendAddButton = $("button[name=add_channel_signal_btn]");
                $sendAddButton.bind("click", function (event) {
                    Record.Signal_Util.sendAddRecordChannelSignal();
                });

                //修改请求
                /*var $sendEditButton = $("button[name=edit_channel_signal_btn]");
                $sendEditButton.bind("click", function (event) {
                    Record.Signal_Util.sendEditRecordChannelSignal();
                });*/

                //新建
                $("button[name=open_new_dlg_btn]").bind("click", function (event) {

                    $("form[role=addForm]").dialog("open");
                    $("form[role=addForm]")[0].reset();

                });

                //取消
                $("button[name=cancel_btn]").bind("click", function (event) {
                    $("form[role=addForm]").dialog("close")
                });
            },

            initGrid: function (options) {
                var self = this;
                self.$grid = self.options.$grid;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.CHANNEL_SIGNAL_DATA_LIST);
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);

                //简单响应式
                // $(window).resize(function(){
                //     self.$grid.setGridWidth($(window).width()*0.9);　
                // });

            },
            query: function (callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            getParam: function () {
                var channelId = Ancestor.Util.getUrlId("channel_id");
                var params = {paramsObj: JSON.stringify({'EQL_recordChannelSignal.channel_id': channelId})};
                console.log("query params:" + JSON.stringify(params));
                return params;
            },
            initDlg: function () {
                $("form[role=addForm]").dialog({
                    title: "关联信号",
                    autoOpen: false,
                    height: 640,
                    width: 840,
                    modal: true
                })
            },
            initSuggest: function () {
                var signalSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/record/signal/libraryList");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        select: function (event, object) {
                            var obj = { "clusterName": Number(object.item.id) };
                            return true;
                        },
                        source: "/api/record/signal/libraryList",
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var param = {"paramsObj": JSON.stringify({'EQL_recordSignal.status':"1",'LIKES_recordSignal.signal_name': $.trim(term)})};
                            return param;
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }

                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["signalName"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }
                $("input[name=signal_name]").suggest(signalSuggest.options);
            }
        });

    }
);
define(
    '../record/Record.ChannelSignalTableGrid',['require','exports','module'],function (require, exports, module) {

        Record.ChannelSignalTableGrid = function (options) {
            this.dao = Record.Dao;
            this.config = Record.Config;
            this.util = Record.Util;
            this.task = Record.Task;
            this.options = options || {};
        };

        Com.inherits(Record.ChannelSignalTableGrid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;
                var taskArr = [];
                taskArr.push(self.task.getLegoCategory("lego_category"))
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.bindEvent();
                    self.initDateTimePicker();
                    self.initSuggest();
                    self.initGrid();
                    self.initSelect();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            bindEvent: function () {
                var self = this;

                $("button[name=query_btn]").bind("click", function (event) {
                    self.query();
                })

            },
            initDateTimePicker: function () {
                EpgWeb.Util.bindDate("'GES_video.create_time'", "'LES_video.create_time'");

            },

            initSuggest: function () {
                var self = this;
                var channelSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/record/channel/list");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        source: Record.urlConfig.getRecordChannelUrl,
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var jsonObj = { LIKES_channelName: $.trim(term), EQI_status: 1 };
                            return { "dataMode": "simple", paramsObj: JSON.stringify(jsonObj) }
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["channelName"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }

                // $("input[name='LIKES_channel.channel_name']").suggest(channelSuggest.options);

                var emailSuggest = {
                    options: {
                        source: Record.urlConfig.redirectUrl,
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: Record.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["email"];
                                itemData[options.labelKey] = item["userName"]
                                itemData["value"] = item["userName"];
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label + "(" + item.id + ")";
                        }
                    }
                }
                // $("input[name='LIKES_channelSignal.op_user']").suggest(emailSuggest.options);

            },
            initGrid: function (options) {
                var self = this;
                self.$grid = self.options.$grid;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.CHANNELSIGNALTABLE_DATA_LIST);
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);

                self.query();
            },
            query: function (callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            getParam: function () {
                var params = {};
                var inputArr = $('form[role="queryForm"]').find("input[role=query-text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("name")] = element.value.trim()
                    }
                })
                var selectArr = $('form[role="queryForm"]').find("select[role=query-select]")
                $.each(selectArr, function (i, element) {
                    if (element.name != "query-repeat-code") {
                        if (element.value.trim().length > 0) {
                            params [$(element).attr("name")] = element.value.trim()
                        }
                    }
                })

                console.log("params:" + JSON.stringify(params));
                return { paramsObj: JSON.stringify(params) };
            },
            initSelect: function () {
                var resultData = Record.Dao.getDataByName("lego_category");
                var filterArr = [];
                $.each(resultData.data, function (i, element) {
                    filterArr.push({ key: element.id, val: element.name})
                })
                var selectJDom = $("select[name='EQI_col.category_id']");
                $("<option value=''>全部</option>").appendTo(selectJDom);
                $.each(filterArr, function (index, obj) {
                    $("<option>", {
                        value: obj.key,
                        html: obj.val
                    }).appendTo(selectJDom);
                });
            }

        });

    }
);
/**
 * Copyright 2015 Qiyi.com All rights reserved.
 *
 * file: epg.js
 * path: js-src/
 * description: epg业务合并文件，通过该文件引入业务功能模块的js文件
 *              配置文件将用来生成合并文件
 * author: jiegang@qiyi.com
 * date: 2015-1-6
 */
define(
    'record', [
        "../entrance_record/Ancestor",
        "../entrance_record/Ancestor.Auth",
        "../entrance_record/Ancestor.Grid",
        "../entrance_record/Ancestor.Config",
        "../entrance_record/Ancestor.Util",
        "../entrance_record/Ancestor.Dao",
        "../epg2/EpgWeb",
        "../epg2/EpgWeb.Util",
        "../epg2/EpgWeb.Plugin",
        "../epg2/EpgWeb.Dao",
        "../epg2/EpgWeb.Task",
        "../record/Record",
        "../record/Record.PlanGrid",
        "../record/Record.TaskGrid",
        "../record/Record.Config",
        "../record/Record.Util",
        "../record/Record.Dao",
        "../record/Record.Action",
        "../record/Record.ChannelGrid",
        "../record/Record.Task",
        "../record/Record.Signal_Action",
        "../record/Record.Signal_Config",
        "../record/Record.Signal_Grid",
        "../record/Record.Signal_Util",
        "../record/Record.Channel_Signal_Action",
        "../record/Record.Channel_Signal_Grid",
        "../record/Record.Signal_Util",
        "../record/Record.ChannelSignalTableGrid"
    ],

    function() {
        console.log('record load done:', 'record');
        if (SystemDialog && SystemDialog.initSystemDialog) {
            SystemDialog.initSystemDialog();
        }
    }
);

